Javascript Cheese

So I’ve been playing a little with unobrusive Javascript. This means that in your page code (we’ll assume XHTML) you don’t have any ugly JS references or calls. You assign attributes and function calls via Javascript.

For example - lets say I have a table on the page, and I want to assign all the tr and td tags some onmouseover and onmouseout events. I might do something like this:


thetrs = document.getElementsByTagName('tr');
thetds = document.getElementsByTagName('td');
status = "lit";
for(i=0; i<thetrs .length; i++)
{
if(status=="lit")
{
thetrs[i].setAttribute('onmouseover','this.className=\"unlit\"');
thetrs[i].setAttribute('onmouseout','this.className=\"lit\"');
thetrs[i].setAttribute('class','lit');
status = "unlit";
}
else
{
thetrs[i].setAttribute('onmouseover','this.className=\"lit\"');
thetrs[i].setAttribute('onmouseout','this.className=\"unlit\"');
thetrs[i].setAttribute('class','unlit');
status="lit";
}
}
for(i=0; i<thetds.length; i++)
{
thetds[i].setAttribute('onmouseover','this.className=\"tdlit\"');
thetds[i].setAttribute('onmouseout','this.className=\"tdunlit\"');
thetds[i].setAttribute('class','tdunlit');
}

Pretty sweet stuff. You can go further by working with nodes, childNodes and insertAfter. Maybe I’ll write up a solid tutorial for all you kiddies.

I think JS has been overlooked for a long time, and with the advent of fresh buzz (AJAX..ug…I hate that word) it is getting some attention.

Sweet, sweet JS cheese.


  1. Wesley

    That’s pretty cool. I like where this could go. One could remove the scripting from the html template and then in an external js file just set the js events based on class names just like css does for styles. I wonder if this sort of activity creates any sort of increased loading latency on slower computers. You would need to be careful though as it would be easy to overcomplicate things using this style of coding.

Leave a Comment




www.flickr.com
smithellis' items Go to smithellis' photostream