I am currently working on a site that has thousands upon thousands of lines of jQuery code, there are a lot of click events especially and I was wondering is there a more performance-aware, best practice out there for binding click events or any event to an item.
Surely having 30+ click events on various links and items cannot be good performance wise being registered. The new jQuery 1.7 "on" function is being used, should perhaps the events be bound to the body element or something and then a check will get the item being clicked and then work from there? Or is it a non-issue and binding a lot of events not really an issue for a modern browser or performance?
bind() method is used for attaching an event handler directly to elements.
jQuery's event system requires that a DOM element allow attaching data via a property on the element, so that events can be tracked and delivered. The object , embed , and applet elements cannot attach data, and therefore cannot have jQuery events bound to them.
The jQuery bind() event is used to attach one or more event handlers for selected elements from a set of elements. It specifies a function to run when the event occurs. It is generally used together with other events of jQuery. Syntax: $(selector).
The bind() is an inbuilt method in jQuery which is used to attach one or more event handlers for selected element and this method specifies a function to run when event occurs. event: This is an event type which is passed to the selected elements.
You should bind the elements to the lowest dom element that contains all of the clicked elements.
So if there's a div called foo
that contains every single element, you'd say:
$("#foo").on("click", "yourselector", function(){
});
If the your elements are spread across every inch of your page, then you'd listen at the very top:
$(document).on("click", "yourselector", function(){
});
If I'm understanding your question correctly, I really really hope the previous developer didn't do something like:
$("#someButtonId").on("click", function(){
//this defeats the whole purpose of on!!!
});
You can bind the same event more than once on an element, but if you are having as much as 30 click events on the same link, you should do it differently. Put the code for all those different actions that you want to do in a single event handler instead of binding every little thing by themselves.
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