tags:

views:

24

answers:

1

I have a page with news item titles, clicking each one ajax loads a full news items including a photo thumbnail. I want to attach a lightbox to the thumbnails to show a bigger photo.

I have two options (i think):

  1. .live()

.

$('img .thumb').live('click', function())
  1. add a specific id based listener on callback of the news item click

.

$('div.news_item').click(function(){
    var id = $(this).attr('id');
    //click
    show_news_item(),
    //callback
    function(){$(id+' .thumb').lightbox();}
})
+1  A: 

In .live() you have 1 listener instead of n event listeners bound, so that's usually a win right there, provided you have:

  1. A large number of elements or, dynamically created/loaded elements
  2. Nesting in the DOM isn't too deep, or is but you have a lot of elements (cost/benefit ratio here)

In your case I would use .live(), like this:

$('div.news_item').live('click', function(){ });

Or, if your class="news_item" elements are in a container that you can select like this:

<div id="newsItems">
  <div class="news_item">News 1</div>
  <div class="news_item">News 2</div>
</div>

You can use .delegate() like this (even more efficient, less event bubbling up the DOM):

$("#newsIems").delegate(".news_item", "click", function() { });

Note: the code inside your function is still the same, $(this) still points to the same element with either of these options.

Nick Craver
@Nick Craver +1 very nice explanation as always
c0mrade
so 1x loose .class listener on the body (.live()) or on a more localised element(.delegate()) would be more efficient than say 6 (avg num of newsitems a user will click) specific #ID based listeners added on callback?
Haroldo
@Haroldo - Kinda...there are a lot of factors here, for example are there click handlers on the parents, etc. However...you're rigging up the click event whether they click it or not, so how many they click doesn't matter, it's the startup time that you'll eat with a large number of elements. Based on your comment of 100-150 items, **yes** `.live()` or the better `.delegate()` is **far** better/more efficient.
Nick Craver
@nick - fantastic, thanks nick. I've always used .live() without really thinking about it, but i guess a few body listeners is definitely better than 100 element listeners with initializing. thanks again
Haroldo