Amoeba
Amoeba

Reputation: 1583

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>'
});

Upvotes: 2

Views: 1273

Answers (3)

Joe
Joe

Reputation: 15558

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
}

Upvotes: 4

PSL
PSL

Reputation: 123739

Try use event delegation, for dynamically created elements. Your hover event is bound only to the element that exists at that point in time, since you are appending them at run time you need to either bind the event again for newly added rows or use eventdelegation to have your container delegate the event to the dynamic rows when available.

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

event-delegation

hover is a virtual event for the combination of mouseenter/mouseleave.

Demo

Upvotes: 3

user2437417
user2437417

Reputation:

Use CSS instead of JavaScript for simple style changes on a hover event.

#my_table > tbody > tr:hover {
    background: yellow;
}

But if you did use JavaScript, I'd suggest creating the element, and binding directly to it.

Since hover events happen so frequently as the mouse moves, I'd want to keep the handler as close to the element as possible.

$('<tr class="table_row"><td>' + results + '</td></tr>')
    .hover( function() {
        event.preventDefault();
        $(this).toggleClass('highlighted');
    })
    .appendTo("tbody");

Upvotes: 3

Related Questions