What’s the difference between Event Handlers & addEventListener in JS?

The difference is subtle but essential to know.

Twan Mulder
Nov 18 · 4 min read

The two ways of handling JavaScript Events

Method 1 — An Event Handler

JavaScript code block showing the use of an event handler
JavaScript code block showing the use of an event handler
Using the onclick event handler to log “Hello!” in the console
const button = document.querySelector(".btn")button.onclick = function() {
console.log("Hello!");
};
// ORbutton.onclick = () => {
console.log("Hello!");
};

Method 2 — An Event Listener

JavaScript code block showing the use of an event listener
JavaScript code block showing the use of an event listener
Using an added click event listener to log “Hello!” in the console
const button = document.querySelector(".btn")button.addEventListener("click", function(event) {
console.log("Hello!");
})
// ORbutton.addEventListener("click", event => {
console.log("Hello!");
})

What’s the difference?

JavaScript code block showing how when you use the “onclick” property of an element twice, it will overwrite the first one.
JavaScript code block showing how when you use the “onclick” property of an element twice, it will overwrite the first one.
Here, the second event handler will overwrite the first one.
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.

So what happens when we use “addEventListener”?

JavaScript code block showing the use of multiple click event listeners.
JavaScript code block showing the use of multiple click event listeners.
Using event listeners, we can call multiple functions when a user clicks on the button.
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?

So what have we learned?

DailyJS

JavaScript news and opinion.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store