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>'
});
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With