Reputation: 369
HTML code:
<ul class="nav-menu">
<li id="no" onmouseover="dropDown()" onmouseout="reverseDropDown()">
<a href="#" >Birds</a>
<ul class="menu">
<li id="no2" ><a href="#" onmouseover="dropDown2()" onmouseout="reverseDropDown2()">Ratites</a>
<ul class="submenu">
<li><a href="">Ratites</a></li>
<li><a href="">Fowl</a></li>
<li><a href="">Neoaves</a></li>
</ul>
</li>
<li><a href="">Fowl</a></li>
<li><a href="">Neoaves</a></li>
</ul>
</li>
<li id="no" onmouseover="dropDown()" onmouseout="reverseDropDown()">
<a href="#">Dogs</a>
<ul class="menu">
<li><a href="">Big</a></li>
<li><a href="">Red</a></li>
<li><a href="">Noizy</a></li>
</ul>
</li>
CSS code:
a {
color: #06c;
}
ul {
padding: 0;
margin: 0;
background: pink;
float: left;
}
li {
float: left;
display: inline;
position: relative;
width: 150px;
list-style: none;
}
.menu {
position: absolute;
left: 0;
top: 100%;
background: #ccc;
display: none;
}
.submenu{
position: absolute;
top:0px;
left:70px;
background: #ccc;
display: none;
}
Javascript code:
function dropDown() {
var submenu = document.getElementById('no').getElementsByClassName('menu')[0];
submenu.style.display="block";
}
function reverseDropDown(){
var submenu = document.getElementById('no').getElementsByClassName('menu')[0];
submenu.style.display="none";
}
function dropDown2() {
var submenu = document.getElementById('no2').getElementsByClassName('submenu')[0];
submenu.style.display="block";
}
function reverseDropDown2(){
var submenu = document.getElementById('no2').getElementsByClassName('submenu')[0];
submenu.style.display="none";
}
JSFiddle: http://jsfiddle.net/wkmd7h0r/33/
I want to make a multi level dropdown menu using javascript ( without libraries such as jquery and without the use of css hover propery, etc).
I have tried in many ways, this is the last one and I can't get it to work. Can someone help me with explanations and/or a tutorial. Cause I did google for one and couldn't find anything except for menus using pure CSS or JQuery.
Thank you.
Upvotes: 1
Views: 8393
Reputation: 3501
first of: You should really use event handlers. Separating logic from code (moving all js into an external file).
i've modified it a bit to reflect a possibility (changed HTML, JS, CSS):
full code here jsFiddle
Most important was, to stop triggering the parent A-tags: putting the onclick function on the link, not it's parent li.
function dropDown(a) {
var li = a.parentElement,
submenu = li.getElementsByTagName('ul')[0];
submenu.style.display = submenu.style.display == "block" ? "none" : "block";
return false;
}
Upvotes: 2