You can add multiple handlers for an event with addEventListener
.
The on___
property or attribute allows to register only one handler. Setting on___
will remove all existing handlers.
In the following sample code, clicking the element will print onclick is used
in Console because
the onclick
removes the original handler
.
const handler = () => {
console.log('addEventListener is used');
};
element.addEventListener('click', handler);
const anotherHandler = () => {
console.log('onclick is used');
};
element.onclick = anotherHandler;
With addEventListener
, it's possible for us to handle the event in either capturing or bubbling phase by passing.
The on___
property doesn't support that.
Assume that we have two div
element as following:
<div id="parent">
Parent
<div id="child">
Child
</div>
</div>
We are going to add handlers for the click
event:
const handleParentClick = () => {
console.log('parent is clicked');
};
const handleChildClick = () => {
console.log('child is clicked');
};
Setting the third parameter of addEventListener
to true
or false
could change the order of handler execution.
document.getElementById('parent')
.addEventListener('click', handleParentClick, false);
document.getElementById('child')
.addEventListener('click', handleChildClick, false);
In contrast with the bubbling phase, the following code will make the click
event is passed from parents down to its children:
document.getElementById('parent')
.addEventListener('click', handleParentClick, true);
document.getElementById('child')
.addEventListener('click', handleChildClick, true);
The last thing is the browser compatibility.
The addEventListener
function doesn't work before Internet Explorer (IE) 9, while onclick
is supported by all browsers.
The IE 8 and older versions use the attachEvent
function.
It isn't really important thing in the web development today as most websites don't support IE 8 or 9 anymore. But if you
still need to take care of IE 8 (really?), then here is the small line of code that fills the gap:
element.attachEvent
? element.attachEvent('onclick', handler)
: element.addEventListener('click', handler);