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.
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.
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 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.