Using jQuery to highlight a table row on mouse over is pretty simple to achieve, and today I’ll quickly demonstrate how you can achieve this neat effect using the addClass and removeClass jQuery functionalities.
First, you need to define your CSS style to be applied to the row you are hovering over, picking out some CSS attributes that you wish to manipulate. In our case, we’re going to be changing the background-color property and thus our CSS style entry looks like this:
.datahighlight {
background-color: #ffdc87 !important;
}
Next, we force all the rows in our table to be a member of a specific class:
Text Row to be highlighted |
Finally, we apply the jQuery code:
$(document).ready(function(){
$('.simplehighlight').hover(function(){
$(this).children().addClass('datahighlight');
},function(){
$(this).children().removeClass('datahighlight');
});
});
As you can see, all the jQuery magic is doing on mouse over of any element with the class ‘simplehighlight’ applied is adding a class ‘datahighlight’ to all the child elements of that selected element (the one being hovered above), in our case those being the actual cells of the row. Seeing as the !important rule is applied to the simplehighlight definition, those cell backgrounds are forced to the new color definition, giving the appearance of a row highlight.
On mouse out, the datahighlight class is removed, forcing all of the child elements (once again our cells) to return to their normal background color schemes.
It’s simple, easy to implement, and highly effective, as shown by the example below: