Highlight Table Rows using Javascript

Web DevelopmentWhen developing web applications with wide tables, it’s often difficult to scroll horizontally and see which row corresponds to which data. This is why most apps limit the width of any table to the width of the page. Still, at times it is necessary to show a large amount of data in a tabular format. This JavaScript scriplet will help add highlight functionality to any HTML table.

The secret to a simple and effective implementation is to use a CSS style to do the heavy lifting of applying the highlight. Instead of manually coloring each cell, a CSS style applied at the row level will properly highlight the cells, and be easy to remove when the next row will need to be highlighted instead. The problem with directly applying the style to the row is that some browsers do not render it properly, so a workaround is needed. We will need to use nested styles to access the cells themselves, as follows:

.xtbl_highlight td

Next, although the work of adding a removing the style could be done by JavaScript directly, it is much easier to leverage the power of jQuery to apply the class to each row:

$(document).ready(function () {
$('#Grid tr').click(function () {
$('#Grid tr').removeClass('xtbl_highlight');

The first command makes sure that the function will be triggered when a row is clicked. Next, we remove the highlight class from any existing row in the table, and finally we add the highlight to the currently selected row.

If it already isn’t installed on the page, we will also need to include the jQuery library itself. This example uses an older jQuery library, however the newer jQuery will run just as well.

<script language="javascript" type="text/javascript" src="/Scripts/jquery-1.6.2.min.js"></script>

This simple script will significantly increase the usability of wide forms that require horizontal scrolling. Just like people often use a ruler to help navigate a wide printed form with many columns, this technique brings that same paradigm to the web in a simple and effective implementation.

Written by Andrew Palczewski

About the Author
Andrew Palczewski is CEO of apHarmony, a Chicago software development company. He holds a Master's degree in Computer Engineering from the University of Illinois at Urbana-Champaign and has over ten years' experience in managing development of software projects.

RSS Twitter LinkedIn Facebook Email

One thought on “Highlight Table Rows using Javascript”

Leave a Reply

Your email address will not be published. Required fields are marked *