One significant difference is that jQuery handlers can be removed without a reference to the handler itself, with off
:
$('div').on('click', () => console.log('clicked'));
$('div').off('click');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>click</div>
This is impossible with addEventListener
- you must a save a reference to the handler in order to remove it. (jQuery saves the reference to the handler internally, when you use .on
)
For example, if you had
window.addEventListener('click', () => console.log('click'));
It would be impossible to remove the listener afterwards, unless you monkeypatched addEventListener
beforehand.
Another significant difference is that jQuery cannot add listeners in the capturing phase, but addEventListener
can:
window.addEventListener(
'click',
() => console.log('Click during capturing!'),
true // <--- enables capturing
);
document.body.addEventListener('click', () => console.log('normal bubbling click handler'));
click
Another difference is that jQuery handlers can be attached to many elements at once with one command, whereas addEventListener
may only be called on a single element. Eg, to emulate
$('div').on('click' ...
when there's more than one div
, you would have to do something like
document.querySelectorAll('div').forEach((div) => {
div.addEventListener('click' ...