Easy Row Highlighting with Prototype

Using the instrumental Prototype library, it is now extremely easy to add unobstrusive row highlighting effects to your HTML tables with a single Javascript function call. What is row highlighting? Quite simply, row highlighting iterates through a collection of table rows and attaches event observers for the OnMouseOver and OnMouseOut events. Once these events are triggered, prototype simply adds or removes a CSS class name that will allow you to style the highlighting effect however you want. The overall effect is a table whose rows light up when you run your mouse over them.

Since prototype is actually adding a classname to your table row instead of replacing the existing one, we don’t have to worry about overwriting other table row styles (such as alternating row colors). This is actually an often unused facet of CSS which allows us to add several classnames to a single element. The properties of each assigned classname are combined and any properties defined in the last class name will always supercede duplicate properties assigned in the classes defined first.

Allow me to illustrate with an example and some code:

Here is a simple HTML table with alternating row styles, pure markup.

Here is some basic styling to make our table look pretty:

Now, this is what our table looks like so far:

Header 1 Header 2 Header 3 Header 4
Data Cell 1 Data Cell 2 Data Cell 3 Data Cell 4
Data Cell 5 Data Cell 6 Data Cell 7 Data Cell 8
Data Cell 9 Data Cell 10 Data Cell 11 Data Cell 12
Data Cell 13 Data Cell 14 Data Cell 15 Data Cell 16

Here is where the magic happens: First, make sure you are pulling in the latest version of the Prototype Library. Second, copy this little Javascript function into one of your included JS files, or just place it inline on the page.

Update (2/14/07) I updated the function to work with Internet Explorer, apparently “this” loses it’s reference when passed as an event function in IE.

It is important that your table contains a TBODY tag, if you don’t use one this function won’t work. Using TBODY is good practice anyway to help semantically seperate your table header, body, and footer.

Now, you can call the highlight rows function at any point in your page and the events will be attached to your table. I recommend attaching it to the window load event. For this example, I will trigger the function using an onclick with the link below.

Click me to attach row highlighting to the above table. After you click that link, go mouseover the table and see if it works.


About this entry


You may also enjoy


Recent comments