Highlight table rows and columns on mouse over

Hovering over the table rows and columns adds a user friendly kind of impression because it improves the readability for the end user .



Firstly construct html table with data

HTML


index.html
<html>
<head>
 <link rel="stylesheet" type="text/css" href="style.css">
 <script  src="http://code.jquery.com/jquery-1.9.1.min.js" ></script>
</head>
<body>
<table border='1' cellspacing='5' cellpadding='5'>

 <tr>
  <th>Header 1</th>
  <th>Header 2</th>
  <th>Header 3</th>
  <th>Header 4</th>
  <th>Header 5</th>
 </tr>

 <tr>
  <td></td>
  <td></td>
  <td></td>
  <td></td>
  <td></td>
 </tr>

 <tr>
  <td></td>
  <td></td>
  <td></td>
  <td></td>
  <td></td>
 </tr>

 <tr>
  <td></td>
  <td></td>
  <td></td>
  <td></td>
  <td></td>
 </tr>

 <tr>
  <td></td>
  <td></td>
  <td></td>
  <td></td>
  <td></td>
 </tr>

</table>
</body>
</html>

CSS


style.css
table { border-collapse: collapse;}
th { color: #fff; background-color: #000000; text-align:center; }
td{height:30px}
.hover{ background-color:#ABCCF2 }

JavaScript


Lets See the highlighting effect on
  1. Highlight rows on hover .
  2. Highlighting columns on hover .
  3. Highlight Both rows and columns on hover.
we make use of jQuery hover function for this .

Syntax

{selector}.hover(function_1,function_2);

           function_1 :   This function called when the mouse is over the matched element .
           function_2 :   This function called when the mouse is out of the matched element .

and we also make  use of  ".not(‘:first’)" which specifies  that the first row should not be considered that the header of the table

1.  Highlight row on hover
 $(document).ready(function(){
    $("tr").not(':first').hover(
       function(){
          $(this).addClass("hover");
       },
       function(){
         $(this).removeClass("hover");
       } );
});


2. Highlight column on hover
$(document).ready(function(){
  $('td').hover(function() {
    var i = parseInt($(this).index()) + 1;
     $('td:nth-child(' + i + ')').addClass('hover');
   },
   function() {
     var i = parseInt($(this).index()) + 1;
     $('td:nth-child(' + i + ')').removeClass('hover');
  });
});

3. Highlight Both Row and Column on Hover
$(document).ready(function(){
   $('td').hover(function() {
     var i = parseInt($(this).index()) + 1;
     $('td:nth-child(' + i + ')').addClass('hover ');
     $(this).parent().addClass('hover');
    },
  function() {
    var i = parseInt($(this).index()) + 1;
    $('td:nth-child(' + i + ')').removeClass('hover ');
    $(this).parent().removeClass('hover');
  });
});

No comments:

Post a Comment