I am trying to make a drop down menu with Javascript (no JQuery). In my HTML, I have an unordered list that contains two list items, each containing an anchor and an unordered list with more list items inside.
I am not concerned about the menus looking pretty, just that the Javascript works. Right now, I am trying to get it to set up event listeners through a while loop so that when the top level list items are moused over, the class of the lower list itemsnwill change from one in which the CSS is set to display:none; to a class that has display:block; to make them appear.
I only have two tabs here, but that is because I shortened it from a list of ten tabs. I also don't care about any further submenus.
JS Fiddle: https://jsfiddle.net/xL5pukd5/
HTML:
<header>
<!-- <ul> <li><a></a><ul> <li><a></a></li> -->
<!-- dd-menu dd-menu-tab dd-menu-tab-anchor dd-submenu dd-submenu-tab dd-submenu-tab-anchor -->
<nav id="dd-menu-container">
<ul id="dd-menu">
<li class="dd-menu-tab">
<a href="link1.htm" class="dd-menu-tab-anchor" title="Link1">Link 1</a>
<ul class="dd-submenu">
<li class="dd-submenu-tab">
<a href="#" class="dd-submenu-tab-anchor">SubLink1a</a></li>
<li class="dd-submenu-tab">
<a href="#" class="dd-submenu-tab-anchor">Sublink1b</a></li>
</ul>
</li>
<li class="dd-menu-tab">
<a href="link2.htm" class="dd-menu-tab-anchor" title="link2">Link2</a>
<ul class="dd-submenu">
<li class="dd-submenu-tab">
<a href="#" class="dd-submenu-tab-anchor">Sublimn2a</a></li>
<li class="dd-submenu-tab">
<a href="#" class="dd-submenu-tab-anchor">Sublink2b</a></li>
<li class="dd-submenu-tab">
<a href="#" class="dd-submenu-tab-anchor">Sublink2c</a></li>
</ul>
</li>
</nav>
</header>
JavaScript:
getTabs = function(elementClass) {
var tabs = document.getElementsByClassName(elementClass);
return tabs
};
getSubmenus = function(elementClass) {
var submenus = document.getElemenetsByClassName(elementClass);
return submenus;
};
window.onload = function {
var tabs = getTabs("dd-menu-tab");
var submenus = getSubmenus("dd-submenu");
var tabNumber = tabs.length - 1;
var currentTab = 0;
while (currentTab <= tabNumber) {
tabs[currentTab].onmouseover = function {
submenus[currentTab].className = "dd-submenu-onmouseover"
};
tabs[currentTab].onmouseout = function {
submenus[curenetTab].className = "dd-submenu"
};
currentTab += 1;
}
};
CSS:
.dd-submenu {
display: none;
}
.dd-submenu-onmouseover {
display: block;
}
I've tried using other prewritten drop down menu methods, but I couldn't get them to work, so I tried to create my own. Thanks in advance to any help :)