views:

233

answers:

1

I've read countless articles how using the JQuery delegate is much more efficient than using the "live" event.

As such, I'm having trouble converting my existing Live code to using Delegate.

$("#tabs li:eq(0)").live('click',function(){ //...code });
$('#A > div.listing, #B > div.listing, #C > div.listing').live('mouseover',function(){ // ...code });

When I replace the previous code with what I assume is more efficient delegate code, my page doesn't load.

$("#tabs li:eq(0)").delegate('click',function(){ //...code });
$('#A > div.listing, #B > div.listing, #C > div.listing').delegate('mouseover',function(){ // ...code });

Any idea why my delegate code doesn't work? Also, any suggestions on how to make this more efficient?

UPDATE:

The think part of the problem is that, both "#tabs" and "#A, #B, #C" are't present on the web page at page load. Those attributes are dynamically inserted onto the page with an AJAX call. As such, does that mean I have to use live over delegate?

+1  A: 

Update for your update :) - Yes, stick with .live() if this is the case, unless your DOM is very deep, there's an infinitesimally small difference in performance.


Previous answer: Your delegate functions should look like this:

$("#tabs").delegate('li:eq(0)', 'click', function(){ //...code });
$('#A, #B, #C').delegate('> div.listing', 'mouseover', function(){ // ...code });

This depends on #tabs not being in the content that's replaced as part of any ajax call, the same for #A, #B, and #C. The format for .delegate() is this:

$(selectorOrNonReplacedParent).delegate(childSelector, event, function);
Nick Craver
@Nick Craver, The problem is that, both *"#tabs"* and *"#A, #B, #C"* are't present on the web page at page load. Those attributes are dynamically inserted onto the page with an AJAX call. As such, when I made the change per your code - my page still doesn't load. Any ideas what's causing my problem?
JacobD
@JacobD - If those aren't present, then you need to either stick with `.live()` or go to a higher ancestor that *does* exist when you're doing this binding. `.delegate()` actually uses `.live()`, it's not a full replacement.
Nick Craver