JQuery: how to use "delegate" instead of "live"?
I have read countless articles on how using the jQuery delegate is much more efficient than using a live event.
So I am having trouble converting my existing Live code to use a 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 consider to be more efficient delegate code, my page won'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 isn't working? Also, any suggestions on how to make this more efficient?
UPDATE
Thought about the problem is that both "#tabs" and "#A, #B, #C" are not present on the web page on page load. These attributes are dynamically inserted into the page using an AJAX call. So, does this mean that I should be using live over delegate?
a source to share
Update for your update :) . Yes, stick .live()
with if that's the case, if your DOM isn't very deep there is an infinitesimal performance difference.
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 });
It depends on what is #tabs
not in the content that has been replaced as part of any ajax call, same for #A
, #B
and #C
. The format .delegate()
is:
$(selectorOrNonReplacedParent).delegate(childSelector, event, function);
a source to share