tags:

views:

273

answers:

2

I'm trying to set a CSS style using .live(). The CSS function:

$(".data tr:odd").addClass("evenrows");

Is there a way for this to happen automatically on document ready but still happen for future elements? I've got an ajax event on the page that re-orders a table. I need these newly created rows to have the .addClass applied to them.

Thanks in advance.

+1  A: 

We've accomplished this by hooking into the Ajax event delegates and doing whatever we want there. See "Complete" here: http://docs.jquery.com/Ajax/jQuery.ajax#options

You would use Live to attach any event handlers to those new rows. See: http://docs.jquery.com/Events/live#typefn

Mark
I was using complete. I just thought there would be a more efficient solution given that right now I have the function that fires when the DOM is ready, then I have to attach it to any ajax calls I have. I'd rather not have to worry about remembering to do that. Also that means I'm writing it over and over for each ajax call. Thoughts?
jeerose
You don't have to write it over, just call the same method in both places.
Mark
+3  A: 

you could use the Livequery plugin. It binds itself to DOM mutation events to track changes in the DOM, and re binds and re executes code attached to them, e.g:

$(".data tr:odd").livequery(function(){
   $(this).addClass("evenrows");
});
pǝlɐɥʞ
@pǝlɐɥʞ, that's a great solution so +1. I still feel like there must be a way to use .live() to do this. The idea is to put the .addClass in $("body").live("load", function(){}); which doesn't work obviously. Is there a solution like this or am I resigned to use a plug-in?
jeerose
@jeerose I'm afraid you would have to use a plugin for this case... Because the jQuery.live() is for binding events only, and what you are trying to do here is clearly not an event
pǝlɐɥʞ
You could find out which event Livequery is binding to on the document, and do your own event delegation on that same event.
Mark
@Mark I'm afraid it's a bit more complicated than that.... DOM Mutation events are not fired (at least not reliably AFAIK) in IE. Livequery takes out the hassle of cross browser DOM mutation events
pǝlɐɥʞ