Skip to content

Instantly share code, notes, and snippets.

@belmer
Last active March 22, 2021 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save belmer/5e433aabbab24086af5c12ce0fb7323c to your computer and use it in GitHub Desktop.
Save belmer/5e433aabbab24086af5c12ce0fb7323c to your computer and use it in GitHub Desktop.
What is the difference between Event handler and addEvenListener

What’s the difference?

There’s a subtle, but important difference between these 2 methods of handling events. If you’ll use the first method, event handlers, the difference is that if you add two event handlers for the same button click, the second event handler will overwrite the first and only that event will trigger. Which takes us to the main learning: For a given element, you can only have one event handler per event type, but you can have multiple event listeners.

Example

Event handler

const button = document.querySelector(".btn")
button.onclick = () => {
  console.log("Hello!");
};
button.onclick = () => {
  console.log("How are you?");
};
// This wil log "How are you?" to the console.

addEventListener

const button = document.querySelector(".btn")
button.addEventListener("click", event => {
  console.log("Hello!");
})
button.addEventListener("click", event => {
  console.log("How are you?");
})
// This wil log 
// "Hello!"
// "How are you?"
// to the console

Which one should you use?

Which method you should use, will depend entirely on your use case.

Do you need to attach more than one event to an element? Will you in the future? Odds are, you will.

That’s why, in general, the use of addEventListener is advised.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment