tags:

views:

118

answers:

3

I'm trying to bind three events to one selector using the live() method, but I can't seem to get it working.

Here's what I have so far, and it works until I add additional table rows:

$("tr:has(td)").live('click',function(event){
      //do stuff
}).live('mouseover',function(){
    $(this).toggleClass('highlight');
}).live('mouseout',function(){
    $(this).toggleClass('highlight');
});

Once I add additional table rows, only the click event works. How can I get all three events to work after adding table rows?

+3  A: 

In your example you're adding a live() on something that is not the object you want by going live().live().live() . This is the way jQuery handles chaining.

What you need to do is :

var $o = $("tr:has(td)");
$o.live('click',function(event){
      //do stuff
});
$o.live('mouseover',function(){
    $(this).toggleClass('highlight');
});
$o.live('mouseout',function(){
    $(this).toggleClass('highlight');
});

Here is an article on chaining

marcgg
Just to clarify, `live()` can only be run directly against a selector (i.e. `$("selector").live()`) which is why your code will work and the OP's code will not work. ( I would +1 if my limit wan't reached :) -- Almost every other selector including events can be chained except `.live()`
Doug Neiner
I've tried that, and it doesn't work either. I just pasted your code in, and the click event works, but the other two do not (after I add table rows dynamically).
croceldon
What happens ? Do you get an error ? Have you tried displaying an alert() to see if the function is called (it might just be your highligh class that is broken) ?
marcgg
Ok - here's the deal: alert() shows that the function is being called. But in the function, I cannot seem to change the background color of the tr element (which is all that the .highlight class did). Toggling the class doesn't work, and using the .css method to change the backgroundColor doesn't work either. Perhaps I should post a new question on this?
croceldon
I'd say that your css should be : .highlight td{background-color:blue;} and not .highlight{background-color:blue;}. If this doesn't fix your problem, you might want to open another question. Also if it did fix, I want extra points damnit ! :)
marcgg
It didn't fix it. The event seems to be firing, but it simply will not change the background-color....
croceldon
A: 

I think you have to do $("tr:has(td)").live() three times - you can't chain it.

Skilldrick
A: 

Instead of using live() you can use event delegation, which is much more elegant:

$('table').hover(function(e) {
    $(e.target).closest('tr').addClass('highlight');
}, function(e) {
    $(e.target).closest('tr').removeClass('highlight');
})
David