Home > Blockchain >  javascript show and hide sub menu on click
javascript show and hide sub menu on click

Time:10-29

I have a nav menu bar.

This nav menu contain a sub menu.

When i click on the li the sub menu appear, but when i click again on the li to hide the sub menu this sub menu doesn't hide but if i click on another li the first sub menu disappear.

What i want to make is when i click on the li the sub menu apear and when i click again the sub menu disappear and if i click on another li that contain the class sub it should close any other sub menu and appear the sub menu of this li

i try toggle, classList.contains, if condition but this not work for me

below an example

let menuLi = document.querySelectorAll('.sub'),
  subMenu = document.querySelectorAll('.sub-menu');

menuLi.forEach((li) => {
  li.addEventListener('click', () => {
    menuLi.forEach((li) => {
      li.classList.remove('active');
    });
    if (li.classList.contains('active')) {
      li.classList.remove('active');
    } else {
      li.classList.add('active');
    }
  })
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  list-style: none;
  text-decoration: none;
}

.navbar {
  display: flex;
  align-items: center;
  gap: 20px;
  height: 60px;
  padding: 10px;
  background: red;
}

.sub {
  position: relative;
}

.sub .sub-menu {
  position: absolute;
  top: 39px;
  left: 0;
  width: 100px;
  display: none;
}

.sub .sub-menu li {
  margin: 10px 0;
}

.sub.active .sub-menu {
  display: block;
}
<ul >
  <li>
    <a href="#">Home</a>
  </li>
  <li >
    <a href="#">Info</a>
    <ul >
      <li><a href="#">Info 1</a></li>
      <li><a href="#">Info 2</a></li>
    </ul>
  </li>
  <li >
    <a href="#">image</a>
    <ul >
      <li><a href="#">img 1</a></li>
      <li><a href="#">img 2</a></li>
    </ul>
  </li>
</ul>

CodePudding user response:

I'd probably just keep previous state, reset state of all and set state accordingly.

menuLi.forEach((li) => {
  li.addEventListener('click', () => {
    const isOpened = li.classList.contains('active')
    menuLi.forEach((li) => {
      li.classList.remove('active');
    });
    if (isOpened) {
      li.classList.remove('active');
    } else {
      li.classList.add('active');
    }
  })
});
  • Related