Tutorials JavaScript Table Highlight

Table Highlight

Today's tutorial shows how to create a plugin to highlight table data.

Code

Copy this code into a JavaScript file and include it in your page, after jQuery.

(function($) {
  $.fn.highlight = function() {
    return this.each(function() {
      var table = $(this);
      var cell  = table.find('td');
      
      cell.hover(function() { // hover on
        var index = $(this).index();
        
        // Row hover
        $(this).parent('tr').children().addClass('hover');
        
        // Column hover
        table.find('tr').each(function() {
          $(this).children().eq(index).addClass('hover');
        });
        
        // cell hover
        $(this).addClass('activeHover');
      },
      function() { // Hover off
        var index = $(this).index();
        
        // Row unhover
        $(this).parent('tr').children().removeClass('hover');
        
        // Column unhover
        table.find('tr').each(function() {
          $(this).children().eq(index).removeClass('hover');
        });
        
        // cell unhover
        $(this).removeClass('activeHover');
      }); // End hover
      
    }); // End each loop
  } // end highlight
})(jQuery); // End jquery

Call the plugin

You need to bind the plugin to a table for it to work.

$('table').highlight();

Style

The above plugin adds the class "hover" to the row and column's table data tag. It also adds the class "activeHover" to the current mouse over item. You can style these classes with CSS.

.hover {
  background-color:#ddd;
}
.activeHover {
  background-color:#ccc !important;
}

Now you can make your tables easier to read.

Posted by on . Category: JavaScript


Comments

No comments posted yet

You need to register or login to post new comments.