How to highlight table row record on hover with jQuery
Published: May 23, 2010 , Updated: May 12, 2010 , Author: mkyong
jQuery comes with a hover() mouse event to allow attach two event handlers to the matched elements, executed when the mouse enters and leaves the matched elements.
$("#id").hover(A, B);- A – function to call when the mouse enters the matched element.
- B – function to call when the mouse leaves the matched element.
This is a best function to highlight a table row record. See the jQuery snippet code :
$("tr").not(':first').hover(
function () {
$(this).css("background","yellow");
},
function () {
$(this).css("background","");
}
);It will highlight the table row record on hover, with color of yellow. The “.not(‘:first’)” is common implementation to avoid highlight the header row record.
Try it yourself
<html> <head> <script type="text/javascript" src="jquery-1.4.2.min.js"></script> </head> <body> <h1>Highlight table row record on hover - jQuery</h1> <table border="1"> <tr><th>No</th><th>Name</th><th>Age</th><th>Salary</th></tr> <tr><td>1</td><td>Yong Mook Kim</td><td>28</td><td>$100,000</td></tr> <tr><td>2</td><td>Low Yin Fong</td><td>29</td><td>$90,000</td></tr> <tr><td>3</td><td>Ah Pig</td><td>18</td><td>$50,000</td></tr> <tr><td>4</td><td>Ah Dog</td><td>28</td><td>$40,000</td></tr> <tr><td>5</td><td>Ah Cat</td><td>28</td><td>$30,000</td></tr> </table> <script type="text/javascript"> $("tr").not(':first').hover( function () { $(this).css("background","yellow"); }, function () { $(this).css("background",""); } ); </script> </body> </html>
Note : You can find more similar articles at - jQuery Tutorials





[...] Highlight row of JSF datatable I want to highlight row into JSF table when the mouse pointer is on the row. I found this tutorial. [...]
Good job, thanks for posting this.
My rows and colums are created dynamically. I pasted your code within mine and the are not highlighted. Any idea how I oculd get around this?
hello Mkyong
this is a great way to take attention of users to an exact row hovered.
but Im having trouble why implementing this method to my project.
Lets say I have two php pages called a.php and b.php. in a.php, I allow user to enter some desired data to be search over database and display to them. So the input data are sent and receive over XMLHTTP(ajax).All database functions are implied in b.php and prints a table related to output data. Since b.php is displayed in a.php, when hovering mouse the roe highlighting is not working. I used bunch of manipulation over the code but I failed every each try.
What might be the problem with this?
Edit:Implementation of css to the a.php.(Since b.php is displayed in innerHTML of a div in a.php, I didnt link css to the b.php)
If there are multiple tables how to restrict hover to work for a particular table only
May be you can try assign id to each table, and attached the jQuery event to the specified id only.