Dwayne Charrington
Dwayne Charrington

Reputation: 6622

What is the best approach to binding jQuery events to elements

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?

Upvotes: 5

Views: 396

Answers (2)

Guffa
Guffa

Reputation: 700232

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.

Upvotes: 1

Adam Rackis
Adam Rackis

Reputation: 83358

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!!!
});

Upvotes: 5

Related Questions