JQuery.live () and .each () with AJAX polling

I have a simple function that goes through the page and adds a CSS class to every element that matches using .each() . I am also constantly updating the page with AJAX, and after the first AJAX update that changes things, the function is no longer applied.

code:

 $("div.col-conversation span.label-sticky").each(function () { $(this).closest('li').addClass('stickyhighlight'); }); 

I understand why it does not work after the first AJAX event and tried to use .live() or .delegate() , but it does not seem like you can bind things that are not events (i.e. you can only bind to a click, freezing, etc.) using this method, so .each() will not work.

Is there an easy way to execute this function without including it in the callback with AJAX success and without using a plugin like livequery, which is likely to be redundant?

+4
source share
2 answers

I think this will work for you:

 $('body').on('mychange','div.col-conversation span.label-sticky',function () { $(this).closest('li').addClass('stickyhighlight'); }); 

Add this to your ajax success function:

 $('body').trigger('mychange'); 

OR, if you really do not want (or cannot) change the ajax success function:

 setInterval(function() { $('div.col-conversation span.label-sticky').each(function () { $(this).closest('li').addClass('stickyhighlight'); }); },100); 
+1
source

What is probably better than binding an event handler for each matching element is to attach an event using jQuery.on () with a selector parameter. This allows you to do something like:

 $('#container').on('click', '.yourClass', function(event){ doStuff(); }); 

with

 <div id="container"> <span class="yourClass">...</span> <div class="yourClass">...</div> <anything class="yourClass">...</anything> </div> 

This means that only one event listener should be active, and not one event per element with a class. It also means that if you add items to the container, you will not need to update the listener. This improves productivity and is easier to manage.

Check jQuery.com for more information on .on ().

+1
source

All Articles