Allow me to suggest a more concise and sophisticated approach:
Utilizing delegated mouse events:
$('#mainTable').on('mouseenter mouseleave', 'tr', {el: false}, function (e) {
var hl = e.data.el;
hl && hl.removeClass('hover');
e.data.el = (e.type === 'mouseenter') ?
$(this).addClass('hover') :
$(this).parent().closest('tr:hover').addClass('hover');
});
This method stores the currently highlighted node in a persistent delegated data object and manages the mouse events with the following logic:
- When the mouse enters an element (the innermost hovered
tr
), remove the current highlight and highlight the current element.
- When the mouse leaves an element, highlight the closest
hovered
ancestor tr
instead of the current one.
The primary benefits of using event delegation solutions like $.delegate()
and $.on()
with a selector include having just a single event listener (as opposed to potentially numerous listeners with traditional methods) and the ability to accommodate dynamic changes to the element.
I opted for this solution over using the mouseover
event because I believe the enter/leave events offer better performance, as they do not bubble.
Please note:
There is an issue with jQuery 1.9.x, but it functions properly with other versions I tested, including newer and older releases. This problem arises from an inconsistency with the :hover
pseudo-selector in that particular version.
CSS4
CSS level-4 proposes a feature that could facilitate this behavior using CSS exclusively:
tr, !tr:hover tr:hover {
background-color: transparent;
}
tr:hover {
background-color: #DDFF75;
}
Although this feature is not yet finalized and lacks support from major browsers currently, this section will serve as a reference for future advancements.