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 ?
?
You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.
jQuery delegate() Method Use the on() method instead. The delegate() method attaches one or more event handlers for specified elements that are children of selected elements, and specifies a function to run when the events occur.
Event Delegation is basically a pattern to handle events efficiently. Instead of adding an event listener to each and every similar element, we can add an event listener to a parent element and call an event on a particular target using the . target property of the event object.
Can you use .on() in the manner like:
$(document).on('click', '#selector1, #selector2, .class1', function () { //stuff });
Yes, that will work.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With