Highlighting Table Rows with jQuery

When working with a table of data, it is helpful to add some type of highlight to the row to indicate the current row. This is extremely easy to do with a few lines of code in jQuery.

I have a table that has rows with two editable text boxes in them. When one of the text boxes receives focus, the row it is in becomes highlighted. When exiting, the row is no longer highlighted.

I have created a CSS class called highlight that adds a light yellow background:

.highlight { background:#FFFFCC;}

The table is just standard <tr>, <td> and <input> tags. The <input> tags do not have event handlers specified as attributes, they will be added in code.

The code is very simple. Two event handlers are added to all input textboxes, one for focus and one for blur. In the focus, the highlight class is added to the parent <tr> tag of selected texbox. On blur, the class is removed. I used the closest() function, which finds the closest element. It’s a shortcut to using .parent().parent() to get to the <tr> tag of the current row:

$('input').focus(function() {
 $(this).closest('tr').addClass('highlight');
});
 
$('input').blur(function() {
 $(this).closest('tr').removeClass('highlight');
});

 

The event handlers are added to all <input> tags. You will want to get more specific with the selector if you need to narrow down which elements cause highlighting. In the context of the event handler function, $(this) refers to the element that fired the event (the textbox).

That’s it. With a little CSS and jQuery, the table becomes more usable.

Working example

Leave a Reply

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