Skip to content
Advertisement

How to hide a menu when clicked on any menu-item?

I can not find where is the problem. Any idea about hiding on clicking any menu-item?

var button = document.getElementById("#1");
var menu = document.getElementById("#menu");
button.addEventListener('click', function(event) {
  if (menu.style.display == "block") {
    menu.style.display = "none";
  } else {
    menu.style.display == "block";
  }
});
<ul id="menu">
  <li><a href="#home" id="1" class="active">Home</a></li>
  <li><a href="#model-s" id="1" class="one">Model S</a></li>
  <li><a href="#model3" id="1">Model 3</a></li>
  <li><a href="#modelx" id="1">Model X</a></li>
  <li><a href="#modely" id="1">Model Y</a></li>
</ul>

Advertisement

Answer

You cannot get document.getElementById("#1") with #. getElementById is already an id selector, so you don’t need to have #.

menu.style.display, you don’t have inline styles for menu, your condition won’t pass for the first time.

You also cannot have multiple id in your elements because id should be unique. In that case, you should use class instead (I added menu-item classes for element selectors)

I’ve tried to change your code with some comments

//get all menu items
var menuItems = document.querySelectorAll(".menu-item");
var menu = document.getElementById("menu");
for (const menuItem of menuItems) {
  //add click events to menu items
  menuItem.addEventListener('click', function(event) {
    //hide menu if click on menu item
    menu.style.display = "none";
  });
}
<ul id="menu">
  <li><a href="#home" class="active menu-item">Home</a></li>
  <li><a href="#model-s" class="one menu-item">Model S</a></li>
  <li><a href="#model3" class="menu-item">Model 3</a></li>
  <li><a href="#modelx" class="menu-item">Model X</a></li>
  <li><a href="#modely" class="menu-item">Model Y</a></li>
</ul>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement