What is the best way to bind an event handler to an element in jQuery for performance?
All elements to which I want to bind an event handler are static and we do not have generated and dynamically created elements:
<div class="foo"></div> <div class="bar"></div> <div class="qux"></div>
I want to add a click event handler for all of them separately, I have three options.
I. Attaching an event handler directly
In this classic method, I will bind an event handler directly to the elements:
$('.foo').on('click', f); $('.bar').on('click', g); $('.qux').on('click', h);
II. Attaching an event handler to the parent member multiple times
In this method, instead of the previous one, I attach the event handler to the parent, several times, for each element:
$('body').on('click', '.foo', f); $('body').on('click', '.bar', g); $('body').on('click', '.qux', h);
III. Attach an event handler to the parent just once
This method is similar to the previous method, except for one difference. I will connect the event handler only once, and I will check the desired selectors in the handler itself:
$('body').on('click', function (e) { var $elem = $(e.target); if ($elem.is('.foo')) { f(); } else if ($elem.is('.bar')) { g(); } else if ($elem.is('.qux')) { h(); } });
I want to know which one is the best as performance?