I am trying to create a dropdown menu in javascript (vanilla). I know how to do it in CSS, but i will never really understand Javascript if i don't try to do things in Javascript, hence the question.
My issue is that i cannot work out how to use the array from getElementsByClassName
and loop it to target only the <li>
that was clicked. I have googled until my head hurts, This is due to a lack of understanding/knowledge on how to get/use arrays with an onclick
event with a loop. If someone could kindly help me out with this
function startUp() {
subMenu();
}
function subMenu() {
var menu = document.getElementById('Menu').addEventListener('click', subMenu);
var drop = document.getElementsByClassName('sub');
for (i = 0; i < drop.length; i++){
drop += drop.length;
if (drop.style.display === 'none') {
drop.style.display = 'inline-block';
}else {
drop.style.display = 'none';
}
}
}
window.onload = startUp;
<nav id="Menu">
<ul>
<li>Home</li>
<li>Members</li>
<li>Gallery
<ul class="sub" style="display: none;">
<li>link</li>
<li>link 1</li>
<li>link 2</li>
<li>link 3</li>
</ul>
</li>
<li>Contact
<ul class="sub" style="display: none;">
<li>E-Mail</li>
</ul>
</li>
<li>Steam Community</li>
<li>Youtube</li>
</ul>
</nav>
I have tried multiple different variations of code all afternoon, I just cannot seem to get it all to work together, without writing multiple functions for ID's instead of using classes.