Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 479
Dwayne Charrington Avatar asked Dec 18 '11 02:12

Dwayne Charrington


People also ask

What method can you use to bind an event to an element?

bind() method is used for attaching an event handler directly to elements.

What elements can you attach jQuery events to?

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.

What is event binding in jQuery?

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).

What is the purpose of using bind () method in jQuery?

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.


2 Answers

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!!!
});
like image 187
Adam Rackis Avatar answered Sep 29 '22 07:09

Adam Rackis


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.

like image 39
Guffa Avatar answered Sep 29 '22 08:09

Guffa