Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

What's wrong with my Javascript code?

Featured Replies

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 by consh

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.