Highlight row on mouseover in GridView using jQuery

In my previous post, I have posted about "Formatting ASP.NET GridView using jQuery". In this post, I will show you that how to highlight a gridview row on mouseover. See below image. (the image is not showing the mouse cursor, but the cursor is on 3rd row.)

All we need to do is that on mouseover on gridview rows assign any CSS and on mouseout, remove that CSS. Rather than using mouseover and mouseout method seperately, jQuery provides another method named "hover()" which serves purpose of both the methods. Please read more here about hover().

Below jQuery code, will find all the rows of gridview and using hover method it will assign "LightGrey" color on mouseover and then assign "White" color on mouseout.

$(document).ready(function() {
  $("#<%=gdRows.ClientID%> tr").hover(function() {
    $(this).css("background-color", "Lightgrey");
   }, function() {
   $(this).css("background-color", "#ffffff");
  });
});

If your default backgroud color for row is other than white then put that color code instead of white. Simple and cool... Isn't it?

But there is a problem with this code. That is it will assign the mouseover and mouseout effect on header row as well. Try it yourself with above code. So how to resolve it? Well, we need to change above code little bit so that it finds only those rows which are having "td", not "th". To do this, we can use "has" selector of jQuery to find out all the rows which have td. See below jQuery code.

$(document).ready(function() {
  $("#<%=gdRows.ClientID%> tr:has(td)").hover(function() {
    $(this).css("background-color", "Lightgrey");
   }, function() {
   $(this).css("background-color", "#ffffff");
  });
});

Hope you find this post useful.

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...