Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery toggleClass on a table not working

I'm trying to highlight a table row when the mouse hovers over it. So I'm using jQuery's toggleClass() function. It's worth mentioning that the table rows don't exist initially, they're created after an AJAX call to a server and then inserted into the table. The table rows that get created have a class="table_row". Here's my code ...

$('.table_row').hover( function() {
    event.preventDefault();
    $(this).toggleClass('highlighted');
});

For some reason it won't work, nothing happens. The row won't respond to any events. Here's the code I'm using to create the table elements, and this comes before the above code ...

$('tbody').prepend(
    '<tr class="table_row"><td>' + results + '</td></tr>'
});
like image 762
Amoeba Avatar asked Apr 16 '26 09:04

Amoeba


1 Answers

Try using:

$('tbody').on('mouseenter mouseleave', '.table_row', function() {
    $(this).toggleClass('highlighted');
});

This uses .on() to set an event handler for all existing and future .table_row elements. .hover() binds handlers for both mouseenter and mouseleave events so this will work the same as .hover() would.

You could also consider using the CSS :hover pseudo class. However, this might not be what you're looking for if you need to reuse the .highlighted class. Here's an example:

tbody > tr.table_row{ /* regular styles */}
tbody > tr.table_row:hover{
    // the current styles you have in .highlighted
}
like image 105
Joe Avatar answered Apr 17 '26 22:04

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!