A table ruler is a helpful mechanism that allows the user to highlight sections of a selected HTML table every time the mouse is placed over each of its rows. Naturally, this simple rollover effect permits users to keep track of the row currently being viewed, in this way increasing the table’s overall usability. This is the third article in a four-part series on creating table rulers.
Making Table Rulers Work with Multiple Tables - Extending the functionality of the table ruler (Page 3 of 4 )
Frankly speaking, providing the current table ruler with the ability for working with multiple HTML tables is only a matter of modifying the JavaScript application that you saw in the previous section. It’s that simple, really.
Essentially, the improved version of this JavaScript program must first be capable of iterating over all the tables included in a web document, and then be able to apply the corresponding rollover effect on each of them.
To perform this specific task, below I coded a new JavaScript snippet, which shows how to implement the table ruler with all the HTML tables that have been assigned a “ruledtable” CSS class. Here it is:
function displayTableRulers(){
// get all the tables
var tables=document.getElementsByTagName('table');
if(!tables){return};
for(var i=0;i<tables.length;i++){
// check to see if there are tables with 'ruledtable' class name
if(tables[i].className=='ruledtable'){
// get all <tr> elements of ruled table
var trs=tables[i].getElementsByTagName('tr');
// loop over <tr> elements of ruled table
for(var j=0;j<trs.length;j++){
// display table ruler
trs[j].onmouseover=function(){
this.className='ruler';
}
// remove table ruler
trs[j].onmouseout=function(){
this.className='';
}
}
}
}
}
// display table ruler when the web page has been loaded
That’s quite simple to grasp, isn’t it? As shown above, I modified the previous JavaScript application and provided it with the capability of applying a table ruler effect to all of the HTML tables that have a “ruledtable” value for their “class” attribute.
Finally, the effect in question is applied by means of an obtrusive approach, after the web page finishes loading. If you’ve ever thought that building a table ruler that works with multiple tables was a painful experience, I’m glad to say that you were mistaken!
Now that you hopefully understood how the prior JavaScript program does its thing, it’s time to reassemble the pieces that compose this improved table ruler. With that idea in mind, in the last section of this tutorial I’ll be coding a sample (X)HTML file, aimed at demonstrating how the rows of two HTML tables can be highlighted by means of this JavaScript application.
Thus, jump forward and read the next few lines. I’ll be there, waiting for you.