Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
77
rated 0 times [  80] [ 3]  / answers: 1 / hits: 8026  / 10 Years ago, thu, november 6, 2014, 12:00:00

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.


More From » html

 Answers
1

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;
}

[#41436] Wednesday, November 5, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kalias

Total Points: 79
Total Questions: 116
Total Answers: 116

Location: Malaysia
Member since Wed, May 11, 2022
2 Years ago
;