One ruler to help us not get stuck
With a bit of JavaScript / DOM sorcery, we can provide our visitors with the same
functionality for long data tables in HTML, by applying rollover states to the
rows. This could be implemented tediously by hand, of course, but it would be silly to do so. Instead, we will use the DOM to find the rows to highlight on mouseover.
Before we proceed, see the effect in action.
Meet the markup
To avoid the script highlighting every table in the document, we
need to tell it which tables to add the ruler to and which not to. We do this by
giving the tables in question a class with the name “ruler.” Next thing
we need to avoid is rows in the table header and the table footer to be highlighted.
Let’s take a look at a demo table:
<table class="ruler" summary="Table of
my records">
<caption>My Records</caption>
<thead>
<tr>
<th scope="col">Artist</th>
<th scope="col">Title</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ladytron</td>
<td>604</td>
</tr>
[... more content rows here ....]
</tbody>
<tfoot>
<tr>
<td colspan="2">Last updated: 17.03.2004</td>
</tr>
</tfoot>
</table>
And the script to apply the ruler:
function tableruler()
{
if (document.getElementById &&»
document.createTextNode)
{
var tables=document.getElementsByTagName»
('table');
for (var i=0;i<tables.length;i++)
{
if(tables[i].className=='ruler')
{
var trs=tables[i].getElementsByTagName('tr');
for(var j=0;j<trs.length;j++)
{
if(trs[j].parentNode.nodeName=='TBODY'»
&& trs[j].parentNode.nodeName!='TFOOT')
{
trs[j].onmouseover=function(){this.»
className='ruled';return false}
trs[j].onmouseout=function(){this.»
className='';return false}
}
}
}
}
}
}
First, we check to see if the browser supports the DOM; then we get all tables in the
document, and loop through them.
We check to see if the name of the table class is “ruler.” If it isn’t, we skip it and proceed to the next table.
If it is, we take all the table rows and loop through them.
We check to see if the node above the current one is a TBODY (not a TFOOT or THEAD); if it is, we apply a function on mouseover that changes the row’s class name to “ruled.”
Then we wipe the class name clean on mouse-out.
Styling the ruler
To control the effect, all you need to define in
your style sheet is a class for the ruler:
tr.ruled{
background:#9cf;
}
These settings will be applied to every highlighted row inside every table
with the class “ruler.”
If you want to have different rulers for different tables, simply give the
table an ID:
<table class="ruler" id="mytable"
summary="Table of my records">
and in the CSS:
#mytable tr.ruled{
background:#333;
color:#ccc;
}
That’s all there is to it. May your rule be long and happy.
No comments:
Post a Comment