PDA

View Full Version : Advanced javascript help please :)



seb
20-07-2004, 14:47
I'm building a menu, using a nice semantic layout:



<ul id="menu">
<li>News
<ul>
<li><a href="#">News articles</a></li>
</ul>
</li>
<li>Development Managers Area
<ul>
<li><a href="#">Log on</a></li>
</ul>
</li>
<li>Career Development
<ul>
<li><a href="#">Message Board Forum Area</a></li>
<li><a href="#">Fundamentals</a></li>
<li><a href="#">FAQs</a></li>
</ul>
</li>
</ul>


etc.

Now I want to make it work just by linking a javascript file in, which onload runs this kinda thing:



function onover()
{ this.childNodes[0].style.display = 'block';}

function onout()
{ this.childNodes[0].style.display = 'none';}



var menu = document.getElementById('menu');

for (i=0;i<document.getElementById('menu').childNodes. length;i++)
{
var submenu = document.getElementById('menu').childNodes[i].childNodes[1];
var submenuhead = document.getElementById('menu').childNodes[i];

submenu.style.display = 'none';
addEvent(submenuhead,'mouseover',onover,false);
addEvent(submenuhead,'mouseout',onout,false);
}


addEvent is a function that figures out whether to use attachEvent or addEventListener depending on what the browser understands.



function addEvent(obj, evType, fn, useCapture)
{
if (obj.addEventListener)
{
obj.addEventListener(evType, fn, useCapture);
return true;
}
else if (obj.attachEvent)
{
var r = obj.attachEvent('on'+evType, fn);
return r;
}
else
{
alert('Handler could not be attached');

}
}


The function that I pass to this event has to be literally just that, the name of a function, from what I can gather. No parentheses or variables allowed, so I can't pass it anything.

Basically to cut to the chase, it's not understanding "this" in this context. How can I automatically generate this code for each li so it references to its child ul correctly?

Cheers

seb
20-07-2004, 14:54
formatting corrected

YorkshireRam
20-07-2004, 15:00
googlise (http://www.google.co.uk/search?q=cache:NrjvYEZ__MEJ:www.scottandrew.com/weblog/articles/cbs-events+function+addEvent(obj,+evType,+fn,+useCaptu re)&hl=en)

not my bag javascript... :( - but tend to work out bits I need from javascript.com etc... and piece them together.. any how... this guy is using something similar to you regarding cross browser compat. issues - any use?

:)

seb
20-07-2004, 15:02
yep, that's the function I stole :)

Nope, no help at all - that part of the code works fine :P

seb
20-07-2004, 15:27
replacing "this" with "event.srcElement" does the trick. Not sure if that's DOM though?