views:

28

answers:

1

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();}
  • something else?

I'm wondering specifically how much memory and CPU these choices incur.

Thanks in advance.

Trevor Mills

+3  A: 

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();
});
Nick Craver
Even better is `$('body').delegate('div.abundant_class', 'click', function() { ... })` because there's no need to build the jQuery object for all those divs.
Pointy
@Pointy - Even better is `document.body`, but on both points you're getting into micro-optimizing IMO :) Also you can bind a `.live()` handler in the `<head>` even, *outside* a `document.ready` handler, the DOM need not be ready for a `.live()` handler (where `<body>` would need to be), you can attach a `.live()` event handler at a point it'll select no elements that match it ;)
Nick Craver
Well sure, but if he's bothering at all, there's no reason not to avoid traversing all the `<div>` elements. Also `$('body')` is pretty well short-circuited. In my opinion the "live" function should really have always worked the way "delegate" does. *edit* - ok yes all that's true, but it still seems easier to just use "delegate".
Pointy
I agree, the interface for `live()` is basically broken (and obviously won't work properly if the wrapper it's used on was obtained by means other than a simple selector). I prefer `delegate` for this reason as well as the practical issue with unnecessary selector resolution.
bobince
@Pointy - Definitely a valid point, added the `.delegate()` option as well, @bobince - That may be changing, there's a ticket on the table for it IIRC.
Nick Craver