Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript show and hide sub menu on click

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 class="navbar">
  <li>
    <a href="#">Home</a>
  </li>
  <li class="sub">
    <a href="#">Info</a>
    <ul class="sub-menu">
      <li><a href="#">Info 1</a></li>
      <li><a href="#">Info 2</a></li>
    </ul>
  </li>
  <li class="sub">
    <a href="#">image</a>
    <ul class="sub-menu">
      <li><a href="#">img 1</a></li>
      <li><a href="#">img 2</a></li>
    </ul>
  </li>
</ul>

>Solution :

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');
    }
  })
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading