Fixing Browser Incompatibilities in a CSS Drop-Down Menu - Adding JavaScript to correct browser incompatibilities
(Page 4 of 5 )
As you'll surely recall from the prior section, this drop-down menu required the assistance of a JavaScript function to make it work properly in Internet Explorer, because of IE's lack of support for the "hover" CSS pseudo class.
With that concept in mind, below I defined a brand new function. It is called "initializeDropDownMenu()" and it activates/deactivates the "over" class that I created previously for all of the menu items. It turns the menu in question into a truly cross-browser piece of software.
The mentioned JavaScript function looks like this:
function initializeDropDownMenu(){
// get 'navbar' element
var navbar=document.getElementById('navbar');
if(!navbar){return};
// get all menu items
var menuitems=navbar.getElementsByTagName('li');
if(!menuitems){return};
for(var i=0;i<menuitems.length;i++){
// assign 'over' class attribute to each menu item on 'mouseover'
menuitems[i].onmouseover=function(){
this.className+=' over';
}
// remove 'over' class attribute to each menu item on 'mouseout'
menuitems[i].onmouseout=function(){
this.className=this.className.replace(' over','');
}
}
}
// initialize drop-down menu when web page is loaded
window.onload=function(){
if(document.all&&document.getElementById&&document.getElementsByTagName){
initializeDropDownMenu();
}
}
As you can see, the previous "initializeDropDownMenu()" function is tasked with enabling/disabling the "over" CSS class attached to all of the menu items. In doing this, I'm actually emulating native support for the "hover" CSS pseudo class in <li> elements, which makes the menu work as expected with Internet Explorer. Quite simple, isn't it?
Well, at this point I've introduced all the changes required to get this drop-down menu working with most modern browsers. So the last step that needs to be taken is simply putting all the pieces together, so you can see more clearly how they link with each other.
Thus, to see the complete source code that corresponds to this menu, please jump ahead and read the final section of this tutorial. We're almost done!
Next: The modified version of the CSS-based drop-down menu >>
More Style Sheets Articles
More By Alejandro Gervasio