Javascript: Rollover Dropdown Menus
Up until recently I’d never implemented a rollover dropdown menu. Then I just decided to build one from scratch for my employer College Prowler to improve upper-level navigation. Basically, with some simple javascript to hide/show the menu and some CSS to style and position it, you’ve got yourself a simple javascript rollover dropdown menu! The code follows the example implementation below.
The Javascript:
function rolloverMenu(showHide, menu)
{
var link = 'mainLink';
if (showHide == 0)
{
document.getElementById(menu).style.display = 'none';
document.getElementById(link).setAttribute('class', 'mainNav');
document.getElementById(link).setAttribute('className', 'mainNav');
}
else
{
document.getElementById(menu).style.display = 'block';
document.getElementById(link).setAttribute('class', 'selectedRollover');
document.getElementById(link).setAttribute('className', 'selectedRollover');
}
}
This javascript will either hide or show the menu depending on the location of the cursor. The HTML that calls the javascript has a delay on it as well, but you’ll see that later. This javascript also changes the class name of the link so that even though your mouse isn’t technically hovering over that link it will look like it is being hovered over.
The CSS:
#container{
position: absolute;
z-index: 1001;
}
a.mainNav{
color: White;
font-weight: bold;
font-size: 12px;
height: 40px;
padding: 0px 10px;
line-height: 40px;
float: left;
background-color: #1D3E66;
}
a.mainNav:hover{
background-color: #3D6199;
color: #AAAAAA;
}
a.selectedRollover{
color: White;
font-weight: bold;
font-size: 12px;
height: 40px;
padding: 0px 10px;
line-height: 40px;
float: left;
background-color: #3D6199;
}
.rolloverMenu{
float:left;
padding: 10px 10px 6px 10px;
position: absolute;
z-index: 1000;
background-color: #3D6199;
width: 100px;
}
.rolloverMenu#mainMenu{
top: 40px;
}
.rolloverMenu a{
color: White;
font-weight: bold;
font-size: 12px;
line-height: 20px;
}
Change the CSS to fit your own design. I’ve been very specific in this CSS so that it should be easier for you to identify everything. Note that the #container definition is actually very important for an IE6 bug fix. IE6 has issues with z-index when not combined with absolute positioning. Basically, the parent element of the rollover menu needs to have that specific definition.
Lastly, the HTML:
<div id="container">
<a class="mainNav" href="#" id="mainLink"
onmouseover="rolloverMenu(1, 'mainMenu');"
onmouseout="rolloverMenu(0, 'mainMenu');">
College Search
</a>
<div class="rolloverMenu" id="mainMenu" style="display: none;"
onmouseover="rolloverMenu(1, 'mainMenu');"
onmouseout="rolloverMenu(0, 'mainMenu');">
<a href="#">Link 1</a><br />
<a href="#">Link 2</a><br />
<a href="#">Link 3</a><br />
<a href="#">Link 4</a>
</div>
</div>
And that’s that! The HTML link calls the javascript which implements a series of CSS rules that will hide or show the menu of your choice! Have fun!