How many ways to assign event handlers in javascript?

I want to react on events but I can assign a handler only with HTML attribute, like this and I am asking: Are there many other ways to help mw with that so I can try best way suits my needs?

»Javascript @alshakul

» 2 answers  » 55 views   2 likes

Add photos

Abijuru • 3 months ago
way of doing so you can use DOM level 0 or 2 event handlers »

0  Dislike  •  Reply
There is one reply on this!

@Gadrawin • 3 months ago
Eh I got you, man.... Sometimes event handlers put me into complexity but it's only best way to use. I appreciate you!

Gadrawin • 3 months ago
When you are dealing with events, You have 3 ways of handling and reacting on Events. as you are calling "assigning event handlers" Try one method or another 1st way: HTML attribute: Even though this way looks a little bit odd, it can be helpful if you have less code, but you don't have to use it if you have to write lots of code.

<input type="button" onclick="alert('You just clicked me!')" value="Button">"
2nd way: DOM property By using this way, you can add lots of js code as you want but It will not allow you to assign more than one handler of partcular event. but It's more helpful than first way.

<input type="button" id="button" value="Click Button">
  button.onclick = function() {
    alert('Click me please!');
3rd way: addEventListener and removeEventListener methods You can manage handlers using these special methods because I consider it as best way even though it is the longes to write, but It will work better than these above. elem.addEventListener(event, handler[, phase]) to add, removeEventListener to remove.

<input id="btn_id" type="button" value="Click me"/>

  function coming() {
    alert('Good morning!');

  function leaving() {
    alert('Good bye!');

  btn_id.onclick = () => alert("C'mon!");
  btn_id.addEventListener("click", coming); // Thanks!
  btn_id.addEventListener("click", leaving); // Thanks again!

0  Dislike  •  Reply

Back to top

[SHARE THIS POST]: The post's archived Spread it to others!

Posted under this donnektish »
This community is about sharing contents such as questions and answers discussing about Javascript and TypeScript, ES5, ES6
62 people joined this donnektish

Maintain social distancing, to avoid Covid19