Reputation: 424
Can anyone speak to how the different browsers handle the following:
Picture an HTML document essentially rendering content of a static app with lots of data.
<div class="abundant_class">
<div class="abundant_class">
<div class="abundant_class"></div>
<div class="abundant_class"></div>
...
</div>
<div class="abundant_class">...</div>
<div class="abundant_class">...</div>
...
</div>
Imagine O(1000) such elements in the document.
What's the fastest way to assign a click event to all of these elements?
<div class="abundant_class" onclick="javascript:foo()">
$('.abundant_class').click(function(foo();));
$('div').click(function(){if ($(this).hasClass('abundant_class')){foo();}
I'm wondering specifically how much memory and CPU these choices incur.
Thanks in advance.
Trevor Mills
Upvotes: 3
Views: 91
Reputation: 630379
In cases like this use .live()
or .delegate()
, where you shift the load from initial binding to event bubbling (which happens anyway), like this:
$('div.abundant_class').live('click', function() {
foo();
});
This binds one event handler to document
and listens for the click
event to bubble up and acts upon that, if the element the event bubbled from matches the selector.
As per the comment discussion, here's the very optimized version:
$(document.body).delegate('div.abundant_class', 'click', function() {
foo();
});
Upvotes: 4