I am trying to do drop down horizontal menu in JavaScript. It’s works fine on Firefox and Chrome, however giving me troubles in IE.
Here is the code I have:
function init(){
hideAllSubMenu();
var menuItem = document.getElementById("menu_wrap").getElementsByTagName("div");
for(var index = 0; index < menuItem.length; index++)
{
// if firefox and all oother browsers
if(typeof menuItem[index].addEventListener != "undefined")
{
menuItem[index].addEventListener("mouseover", ShowListener, false);
menuItem[index].addEventListener("click", ShowListener, false);
}
else //IE
{
menuItem[index].attachEvent("onclick", ShowListener);
menuItem[index].attachEvent("onmouseover", ShowListener);
}
}
}
function ShowListener(event)
{
hideAllSubMenu();
var menuItemIdStr = this.id;
var menuItemIdNum = menuItemIdStr.replace(/menu/i, "");
var subMenu = document.getElementById("submenu_wrap" + menuItemIdNum);
subMenu.style.left = this.offsetLeft + "px";
subMenu.style.top = this.offsetTop + this.offsetHeight + 2 + "px";
subMenu.style.display = "block";
}
It’s seems like its complaining about this.
I understand that in IE event listener function is not copy but a reference, and that’s why this giving me a problem.
Is there a way around this problem?
I even tried to create separate function for attachEvent for IE and path there object directly, however it still complaining.
Something like that:
menuItem[index].attachEvent("onmouseover", ShowListenerIE(menuItem[index]));
Note: I do plan to rewrite this simple menu in feature to jQuery, but for now I am interested in learning JavaScript Core + DOM, and would like to find a way around this problem.
The target of an event in IE is in
event.srcElement, and you can get similar information in other browsers fromevent.target. Note also that IE won’t pass event as an argument to the handler – it’s inwindow.eventinstead. So, a complete solution:See here for more gory details. Disclaimer: my code is untested.