addEventListener vs onclick: Which one should you use?
AddEventListener() and onclick both listen for an event. Both can execute a callback function, when a button is clicked. However, they are not the same. Below is a brief explanation of each one to help you figure out which one to use.
The main difference is that onclick is just a property. Like all object properties, you may have one inline event assigned. If you write more than once, it will be overwritten.
btn.onclick = () => console.log('button clicked');
addEventListener() on the other hand, can have multiple event handlers applied to the same element. It doesn’t overwrite other present event handlers.
In this example we’re creating an event listener for the button element in const btn. When a click event is heard, the buttonClicked() function is activated and logs ‘button clicked’ to the console.
function listenToButtonClick() {
const btn = document.createElement('button');
btn.addEventListener('click', function buttonClicked(e) {
console.log('button clicked');
})
}
Which one should you use?
If you need to attach more than one event to an element, you’re probably looking to use addEventListener(). Although people don’t recommend using onclick events, they are quick and do the trick.
How to remove event handlers?
To remove an event handler previously registered with addEventListener() method, you can use removeEventListener(). To use removeEventListener() we need to have access to the function that was originally added. In the example below, buttonClicked() is out of scope and we won’t be able to remove it. The following code doesn’t work:
function add() {
const btn = document.createElement('button');
btn.addEventListener('click', function buttonClicked(e) {
console.log('button clicked');
})
}function removeClickEvent() {
//this doesn't work because buttonClicked is out of scope
btn.removeEventListener('click', buttonClicked);
}
To remove the event from the function buttonClicked() we would write the following code:
const btn = document.createElement('button');
btn.addEventListener('click', function buttonClicked(e) {
console.log('button clicked');
})function removeClickEvent() {
btn.removeEventListener('click', buttonClicked);
}
We need access to the event handler to be able to remove it. If the function above was defined as an anonymous function we wouldn’t be able to use removeEventListener(). However, if an anonymous function is defined as a function expression then we would be able to pass in the variable name to remove the event.