Home » Jquery » jQuery .on() with multiple selectors in event delegation?

jQuery .on() with multiple selectors in event delegation?

Posted by: admin January 30, 2018 Leave a comment

Questions:

I have using .on() in jQuery 1.7 and wondered whether it is possible to attach multiple selectors at a time for elements that have been injected onto a page. Previously, I was using live() – but it’s obvious why I want to move given performance improvements.

Can you use .on() in the manner like:

$(document).on('click', '#selector1, #selector2, .class1', function () { 
     //stuff
});

And are there any benefits lost in attaching to document ?

?

Answers:
  1. Can you use .on() in the manner like:

    $(document).on('click', '#selector1, #selector2, .class1', function () { 
        //stuff
    });
    

    Yes, that will work.

  2. I want to use this instead of live() given performance improvements.

    There are no performance advantages of using that code snippet as opposed to using live(), as live() itself binds events to the document, and in jQuery 1.7, live calls on behind the scenes.

  3. And are there any benefits lost in attaching to document?

    The downside to binding to document is that the event must traverse the entire list of ancestors before it is handled; this, as pointed out in the jQuery documentation, is the slowest possible route. It will be better to handle to event sooner, by attaching the handler to an element closer to the source of the event.

Questions:
Answers:

I think it’s important to read the jQuery source for live to see what’s going on:

live: function( types, data, fn ) {
  jQuery( this.context ).on( types, this.selector, data, fn );
  return this;
}

Notice the on call in there? live has simply turned into an alias for a special case for on.

A good reason to use live instead of on is for selector chaining:

$('#foo').live('click', callback).doSomethingElse()

However, if you’re using live you probably have an empty selection, so it’s a moot point in most situations.

Questions:
Answers:

it’s possible and “this” is the clicked selector, not the document.

you better off attaching to the closest parent element of your selector. When you click on ‘#selector1’, the event bubble up to the event handler element, here: document.

The more layers, the more actions. Moreover, if between selector1 and document there is another click event handler, it can be intercepted with event.stopPropagation();, and never reach the “document” event handler.

you can check the rogue event “interception” in this fiddle.