August 22, 20197 yr Hello, I've been learning Javascript and as a bit of practice, thought i'd create myself a dropdown navigation menu, that works on a 'click' rather than hover. I've created the code below (which doesn't work) and i was wondering if someone could explain why so i can see where i've gone wrong. I can get the dropdown to open, but when i added the code to close the dropdown, the dropdown menu doesn't even open. I'm hoping someonce can point me in the right direction so i can see where i'm going wrong Here's the HTML... <nav class="main-nav"> <ul> <li><a href="" title="Home">Home</a></li> <li class="menu-item-has-children"><a href="#" title="What We Do">What We Do</a> <ul class="sub-menu"> <li><a href="" title="">Page 1</a></li> <li><a href="" title="">Page 2</a></li> <li><a href="" title="">Page 3</a></li> <li><a href="" title="">Page 4</a></li> <li><a href="" title=" ">Page 5</a></li> <li><a href="" title="">Page 6</a></li> </ul></li> <li class="menu-item-has-children"><a href="#" title="Our Work">Our Work</a> <ul class="sub-menu"> <li><a href="" title="">Portfolio 1</a></li> <li><a href="" title="">Portfolio 2</a></li> <li><a href="" title="">Portfolio 3</a></li> <li><a href="" title="">Portfolio 4</a></li> <li><a href="" title="">Portfolio 5</a></li> </ul> </li> <li><a href="" title="">Contact</a></li> </ul> </nav> Here's the Javascript... // Dropdown Menu (function(){ let menuHeader = document.querySelectorAll('.menu-item-has-children'); let subMenu = document.querySelector('.sub-menu'); menuHeader.forEach(function(btn){ btn.addEventListener('click', function(event){ subMenu.classList.add('nav-open'); // Close if anywhere on screen aprt form menu is clicked window.onclick = function(event){ if (!event.target.classList.contains('sub-menu')){ subMenu.classList.remove('nav-open'); } }; }); }); })(); Thanks in advance Ross Edited August 22, 20197 yr by consh
Create an account or sign in to comment