ClanKiller.com
http://forums.clankiller.com/

javascript: crawling the dom for menus
http://forums.clankiller.com/viewtopic.php?f=24&t=2604
Page 1 of 1

Author:  Satis [ Tue Sep 11, 2007 12:39 pm ]
Post subject:  javascript: crawling the dom for menus

yep, I've been playing with javascript quite a bit. Anyway, I have a dynamically generated menu that looks kinda like this.

Code:
<table id='menu'>
<tr><td></td><td><a href='blah0' onmouseover='javascript: highlight(0);'>link0</a></td><td></td></tr>
<tr><td></td><td><a href='blah1' onmouseover='javascript: highlight(1);'>link1</a></td><td></td></tr>
<tr><td></td><td><a href='blah2' onmouseover='javascript: highlight(2);'>link2</a></td><td></td></tr>
</table>

what I wanted to do was automatically put little graphics in the first and last tds on each line as you mouse over it, but I didn't want to write alot of code. You can see the little javascript that the menu requires... and since each line is dynamically generated it's really very little.

The javascript function is this:

Code:
function highlight(targetid){
   var left = '<img src="/intranet/images/left_menu.png">';
   var right = '<img src="/intranet/images/right_menu.png">';
   var menu = document.getElementById('menu');
   for(i=0; i<menu.firstChild.childNodes.length; i++){
      if(i == targetid){
         menu.firstChild.childNodes[targetid].childNodes[0].innerHTML = left;
         menu.firstChild.childNodes[targetid].childNodes[2].innerHTML = right;
      }
      else{
         menu.firstChild.childNodes[i].childNodes[0].innerHTML = '';
         menu.firstChild.childNodes[i].childNodes[2].innerHTML = '';
      }
   }
}


first I set vars for the left and right side graphics, then assign the entire menu to a variable.

I then crawl the dom... I go to the menu's firstchild (which is the tbody tag), then iterate through the childNodes (the tr tags). If the tr tag is a number equal to what's passed into the function I set the left and right tds (childNodes 0 and 2) to the images, otherwise I unset them. Pretty hot! And, even better, it works in both Firefox and IE7.

Author:  Pig [ Tue Sep 11, 2007 12:51 pm ]
Post subject: 

Yeah, you could do it all in CSS if IE7 was teh suck. :(

Page 1 of 1 All times are UTC - 6 hours
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
http://www.phpbb.com/