I am using jquery 1.10. I want to know what the difference is between these three functions.
Which function is better and why?
What is the purpose of the delegate function?
$(".dropdown-menu").on("click", ".show_opt_menu", function() {
alert("hello");
});
$(".dropdown-menu .show_opt_menu").on("click", function() {
alert("hello");
});
$(".dropdown-menu").delegate(".show_opt_menu", "click", function() {
alert("Delegate");
});
Can anybody explain me?
The delegate() Method in jQuery is used to add one or more event handlers to the specified element that are children of selected elements and are also used to specify a function to run whenever the event occurs.
on() method: This method attaches events not only to existing elements but also for the ones appended in the future as well. The difference here between on() and live() function is that on() method is still supported and uses a different syntax pattern, unlike the above two methods.
In short: . bind() will only apply to the items you currently have selected in your jQuery object. . live() will apply to all current matching elements, as well as any you might add in the future. The underlying difference between them is that live() makes use of event bubbling.
Event delegation refers to the process of using event propagation (bubbling) to handle events at a higher level in the DOM than the element on which the event originated. It allows us to attach a single event listener for elements that exist now or in the future.
First off, the third function (.delegate
) has been superseded by .on
(jQuery 1.7 onwards) so I wouldn't use that.
The second method will run the complex selector ".dropdown-menu .show_opt_menu", which is (relatively) expensive as it first gets all .show_opt_menu
s then looks to see which have parents that are .dropdown-menu
. It then binds one event per element. This is (relatively) expensive since you're running a slow query, then binding potentially many events.
The first method is the best, as it binds only one event to .dropdown-menu
then whenever a click
event bubbles up to it, it checks the event to see what the original target was. This is a much cheaper option, and since there's only one event being bound it's a lot more performant.
Summary: #1 is the best, #2 is commonly done but worse, #3 is outdated.
You likely won't notice any performance difference anyway, but it's worth paying attention to anyway because it's good practice. At some point, you may need to concern yourself with performance.
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