PDA

View Full Version : attatching events


allida77
05-08-2003, 09:46 PM
**html
<div id="topmenu">
<span id="mnuItemHome" class="topmenuItem">Home</span>
<span id="mnuItemOrders" class="topmenuItem">Orders</span>
<span id="mnuItemContact" class="topmenuItem">Contact</span>
<span id="mnuItemAdmin" class="topmenuItem">Administration</span>
</div>

**js
var objMnu = document.getElementById("topmenu")

aMnuItems= objMnu.getElementsByTagName("span");

//this will not work
for(i=0;i<aMnuItems.length;i++){
document.getElementById(aMnuItems[i].id).attachEvent("onmouseover",function over(){document.getElementById(aMnuItems[i].id).style.backgroundColor="red"});
document.getElementById(aMnuItems[i].id).attachEvent("onmouseout",function out(){document.getElementById(aMnuItems[i].id).style.backgroundColor="white";});
}



I do not understand why I can not loop through and attach these events. I tried just hard coding the id of the elements and it will work but when I try to loop over them it doesnt work. This may not be the best approach, but I just dont get why its not working.

Graeme Hackston
05-08-2003, 10:30 PM
Try puting the function outside and just this in the loop.

document.getElementById(aMnuItems[i].id).attachEvent("onmouseout",out)

allida77
05-08-2003, 11:04 PM
I need to pass the mnuItem object to the over(obj) function to attach the event. When I do this:

document.getElementById(aMnuItems[i].id).attachEvent("onmouseover",over(document.getElementById(aMnuItems[i].id)));

I get a 'type mismatch' and my page goes into an endless loop.

liorean
05-08-2003, 11:13 PM
The second argument is a function - wrap it in an anonymous function and try again. Also remember that the this keyword can be used within that function to reference the object you add the event listener to.

allida77
05-09-2003, 03:04 PM
I ended up just doing:

function tabItem(obj,href){
this.over = rollovers(obj)
this.href = url(href)

function rollovers(obj){
obj.attachEvent("onmouseover",function getover(){obj.style.backgroundColor="red"});
obj.attachEvent("onmouseout",function getout(){obj.style.backgroundColor="white"});

}

function url(href){
obj.attachEvent("onclick",function over(){location.href=href});
}

}

var tab1 = new tabItem(document.getElementById("mnuItemHome"),'default.html')
var tab2 = new tabItem(document.getElementById("mnuItemAdmin"),'Admin.html')


I looked into anonymous functions and somehow ended up doing this. Thanks for the help because it steered me into the right (or working) direction. This is for ie but I noticed that this does not work in Moz. Is attachEvent proprietary to ie? And if so what is moz's equilivant?

liorean
05-09-2003, 03:30 PM
The W3C DOM equivalent from [DOM2 Events] is addEventListener. It also takes a third argument - whether to catch it in the capture or bubble phase. Set it to false if you want to get the equivalent to the iew proprietary method. (Which doesn't even exist in ie5m.)