I would suggest something a little more elegant (at least shorter):
Using 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'); });
Saves the selected selected node object to a (persistent) delegated data object and processes mouse events as follows:
- If the mouse enters an element (the innermost, hovering
tr ), remove the current highlight and highlight the current element. - If the mouse leaves the item, select the nearest
hovered ancestor tr instead of the current one.
The main advantages of solutions using event delegation (for example, $.delegate() and $.on() with a selector) attach only a single event listener (compared to potentially dozens, hundreds or more using traditional, per-element, methods) and the ability to support dynamic changes for an element.
I chose this solution to use if the mouseover event is because I believe that I / O events should provide better performance because they do not bubble.
Note:
It has a problem with jQuery 1.9.x, but works with the others as far as I tested, including newer and older versions. This is due to a problem with the :hover pseudo :hover in this version.
CSS4
The CSS-4 layer has a suggested feature that can enable this behavior only with CSS:
tr, !tr:hover tr:hover { background-color: transparent; } tr:hover { background-color: #DDFF75; }
Of course, since this function is currently not final and is not supported by any major browser at the moment, this section will serve as reference information.
source share