1

I am trying to capture all the click events on a page.

I can use this:

window.addEventListener('click', function(e){
    console.log(e.target);

}, true);

or

$("*").delegate("*", "click", function(e){
    if (e.target === this) {
        console.log(e.target);
    }
});

What is the difference?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
praks5432
  • 7,246
  • 32
  • 91
  • 156
  • Please refer this: http://stackoverflow.com/questions/8996015/jquery-on-vs-javascript-addeventlistener – pj013 Apr 01 '14 at 18:26
  • `$('*')` will select every single DOM element in the tree and call `delegate` on it. It doesn't make any sense... the equivalent jquery should be `$(window).click(...)`, however note that jQuery doesn't support event capturing so you cannot have something fully equivalent to your first code sample in jQuery. – plalx Apr 01 '14 at 18:38
  • Does this answer your question? [jQuery .on(); vs JavaScript .addEventListener();](https://stackoverflow.com/questions/8996015/jquery-on-vs-javascript-addeventlistener) – Brian Tompsett - 汤莱恩 May 31 '21 at 09:16

1 Answers1

0

There are a couple of differences actually:

  1. You can't use capture for jQuery .on(), such a thing just doesn't exist. jQuery only supports event bubbling. You could, however, specify whether to capture the event in capture phase or bubble phase with .addEventListener()

  2. jQuery .on() allows you to attach the same event listener for multiple events, whereas .addEventListener only allows you to add an event listener to a single event type at a time (although you could use something like

    ["event type 1", "event type 2"].forEach( function(i){ 
            element.addEventListener(i, function(){} ); 
    })
    

    but that's pretty messy)

  3. Maybe you would think that both .on() and .addEventListener() adds event listeners to an event target; it's not that simple, at least not for jQuery. More on that, someone add in details please, because I'm not very clear either :P

  4. Event listeners attached by using .on() can be invoked by calling .trigger(), another jQuery function, but event listeners attached by using .addEventListener() will not respond to .trigger()

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
Shawn Li
  • 419
  • 3
  • 17