Main Tutorials

How to highlight table row record on hover with jQuery

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);
  1. A – function to call when the mouse enters the matched element.
  2. 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>

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
13 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Naidu
8 years ago

How can we add the same thing on click event of the tr? Once click the Link after tr is change color?

Anita
10 years ago

Hi,
Nice article. I have some doubts. Hope you can help me.
I want to get the cell-row no & col no when i hover over the table(4 column table).
My requirement is that in the 2nd cell of each row i have to show a popup describing the values of the 2nd cell (which i hv kept hidden in the 4th cell)

$(‘td’).hover( function( nRow, aData, iDisplayIndex ) {
var iCol = $(‘td’).index(this)%4 ;
console.log(iCol);
var iRow = $(‘tr’).index(this) ;
console.log(iRow);
console.log(aData[iCol]);
$(‘td:nth-child(‘+(iCol+1)+’)’, nTrs).addClass( ‘highlighted’ );
}, function() {
$(‘td.highlighted’, oTable.fnGetNodes()).removeClass(‘highlighted’);
} );

In the above code, i get the col no but my iRow returns -1 and aData[iCol] shows me error as Uncaught TypeError: Cannot read property ‘1’ of undefined

Arun
10 years ago

Now here is another example of Highlighting the table row when the focus is on a textbox control, if any. This too is in JQuery.

http://www.encodedna.com/2013/06/highlight-tablerow-on-texbox-focus-jquery.htm

moraug
10 years ago

You should change not(‘:first’) to not(‘:first-child’).
Your example works only if there is one table. In case of multiple tables each table’s header (except for the first one’s) will be highlilghted also – which is not very good.

travis
12 years ago

Good job, thanks for posting this.

mathieubazinet
12 years ago
Reply to  travis

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?

<script type="text/javascript">
    $(document).ready(function () 
    {
        $("#search").click(function () 
        {
            var empId = $("#criteres").val();
            $.ajax(
            {
                type: "POST",
                dataType: "json",
                contentType: "application/json",
                url: "index.aspx/getCompanies",
                data: "{'ville': '" + empId + "'}",
                success: function (data) 
                {         
                    Success(data);               
                },
                error: function () 
                {
                    alert("Error calling the web service.");
                }
            });
        });

        $("tr").not(':first').hover(
          function () {
              $(this).css("background", "yellow");
          },
          function () {
              $(this).css("background", "");
          }
        );
    });

function Success(data) 
{
       var r = new Array(), j = -1;
       for (var key = 0, size = data.d.length; key < size; key++) 
       {
             r[++j] ='<tr><td>';
             r[++j] = data.d[key].nomEntreprise;
             r[++j] = '</td></tr><tr><td>';
             r[++j] = data.d[key].nom + '&nbsp' + data.d[key].prenom;
             r[++j] = '</td></tr><tr><td>';
             r[++j] = data.d[key].adresse + ',&nbsp' + data.d[key].ville + ',&nbsp' + data.d[key].codePostal;
             r[++j] = '</td></tr><tr><td>';
             r[++j] = data.d[key].telephone;
             r[++j] = '</td></tr><tr><td>';
             r[++j] = data.d[key].fax;
             r[++j] = '</td></tr><tr><td>';
             r[++j] = data.d[key].siteWeb;
             r[++j] = '</td></tr><tr><td>';
             r[++j] = '&nbsp';
             r[++j] = '</td></tr>';         
        } 
    $('#dataTable').html(r.join(''));
}
    

</script>
Giorgio
11 years ago

As nice as simple. Congratulations and thank you so much for sharing!

Eduardo
11 years ago

Thanks a lot, works great and its simple, thanks again.

Cornelius
11 years ago

Great solution! Thank you sir…

secoli
13 years ago

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)

Mukul
13 years ago

If there are multiple tables how to restrict hover to work for a particular table only

maresolaris
11 years ago
Reply to  Mukul

You can add a class or id to each row. Then use $(“tr.CLASSNAME”).not(‘:first’).hover( or $(“tr#IDNAME”).not(‘:first’).hover(.

Works as a charm.

Good luck!