Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - change table row color on hover, getting hover events to work

Tags:

jquery

I want to highlight a table row by changing its color, using jQuery. Have RTFM'd, experimented and researched extensively with little luck.

HTML:

<table id="waypointsTable" border="1">
<tbody>
<tr>
<td>some text</td>
</tr> ...

javascript:

$('#waypointsTable > tbody > tr > td').hover(function() {
    alert(1);
}, function() {
    alert(2);
});

At this point I'm just trying to get the hover functions to fire. Should hover be tied to the tr or the td? Do I always have to include the tbody reference when selecting table rows and td's? Is it better to put a class on each tr or td instead of the above approach?

Thanks.

like image 248
bethesdaboys Avatar asked Nov 01 '11 18:11

bethesdaboys


1 Answers

Looks fine for the most part, if you want to trigger for each row, you can bind to the tr directly.

just:

$('#waypointsTable tr').hover(function() {
    $(this).addClass('hover');
}, function() {
    $(this).removeClass('hover');
});

(full code at http://jsfiddle.net/nicholasstephan/8nbVG/)

should work...

For this case specifically, using a css :hover pseudo selector would do the job too.

#waypointsTable tr:hover {
    background-color:yellow;
}
like image 122
nicholas Avatar answered Oct 02 '22 12:10

nicholas