1

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
});

EDIT

this is not a duplicate of the two suggested question, here I'm looking for differences in this particular case

GJCode
  • 1,959
  • 3
  • 13
  • 30
  • 1
    [jQuery .on(); vs JavaScript .addEventListener();](https://stackoverflow.com/questions/8996015) and [Difference between addEventListener and jquery on?](https://stackoverflow.com/questions/22793858) – adiga May 12 '19 at 08:45
  • Possible duplicate of [What is the difference between JavaScript and jQuery?](https://stackoverflow.com/questions/20283098/what-is-the-difference-between-javascript-and-jquery) – Shubham Dixit May 12 '19 at 08:45
  • @ShubhDixit this isn't a duplicate. The question here isn't about jQuery *as a whole* vs JavaScript *as a whole* but about particular functionality that is seemingly identical between the two. – VLAZ May 12 '19 at 08:49

1 Answers1

2

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' ...
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320