Reputation: 2099
I'm trying to go a little deeper into some javascript aspects. I've just learn jQuery and I was wondering of what differences there are between these two approaches:
pure Javascript:
document.getElementById("myDiv").addEventListener("click", function(){
// do something
});
JQuery
$("#myDiv").click(function(){
// do something
});
this is not a duplicate of the two suggested question, here I'm looking for differences in this particular case
Upvotes: 1
Views: 857
Reputation: 370689
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' ...
Upvotes: 2