How to highlight HTML table rows when mouse cursor hovers over them with jQuery

When I have to look at table of records, I always like to hover my mouse over the row that I am looking at so that I can focus on the details.

In addition, to facilitate my reading of that row, I will want that row to be highlighted as well.

This post describes my exploration to highlight HTML table rows with jQuery.

The css class to style the highlighted row

I first define a css class, rowHighlight, to be used for highlighting the hovered table rows:

.rowHighlight {
    background-color: #f1faff;
}

The jQuery codes for registering interests in mouse hovering event

I then code the jQuery codes to register listeners to the HTML table rows. These listeners will be notified when my mouse cursor hovers over and away from the table rows.

When the cursor hovers over the rows, I add the CSS class, rowHighlight, to the table rows. When the mouse cursor hovers away from the table rows, I remove the css class from the table rows.

$(document).ready(
	function () {
		$('tr').hover(
			function(event) {
				$(this).addClass('rowHighlight');
			}
			, 
			function(event) {
				$(this).removeClass('rowHighlight');
			}
		);
	}
);

The entire HTML document

The web page is pretty easy to construct - I head over to my html reference and did a few copying and pasting. I then add the CSS and jQuery codes that I had prepared earlier in the HTML head section.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>
           HTML table rows highlighted with jQuery when 
           mouse cursor hovers over them
    </title>	
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
	<script type="text/javascript">
		$(document).ready(
			function () {
				$('tr').hover(
					function(event) {
						$(this).addClass('rowHighlight');
					}
					, 
					function(event) {
						$(this).removeClass('rowHighlight');
					}
				);
			}
		);
	</script>
	<style type="text/css">
		.rowHighlight {
			background-color: #f1faff;
		}
	</style>
</head>
<body>
    <table>
	<tr>
		<th>Fruit</th>
		<th>Color</th>
	</tr>
	<tr>
		<td>Apple</td>
		<td>Red</td>
	</tr>
	<tr>
		<td>Kiwi</td>
		<td>Green</td>
	</tr>
	<tr>
		<td>Orange</td>
		<td>Orange</td>
	</tr>
	</table>
</body>
</html>

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.