Home > Software design >  How to show and hide dropdowns using for of loop?
How to show and hide dropdowns using for of loop?

Time:11-10

I have created three custom dropdowns using same classes. I need to open them one at the time, but when I click on one I open all of them.

 <div >
    <p>Open dropdown</p>         
  </div>
  <ul >
      <li>Data 1</li>
      <li>Data 2</li>
      <li>Data 3</li>
      <li>Data 4</li>
      <li>Data 5</li>
   </ul>

 <div >
    <p>Open dropdown</p>         
  </div>
  <ul >
      <li>Data 1</li>
      <li>Data 2</li>
      <li>Data 3</li>
      <li>Data 4</li>
      <li>Data 5</li>
   </ul>

 <div >
    <p>Open dropdown</p>         
  </div>
  <ul >
      <li>Data 1</li>
      <li>Data 2</li>
      <li>Data 3</li>
      <li>Data 4</li>
      <li>Data 5</li>
   </ul>

Javascript

const dropdowns = document.querySelectorAll(".dropdown");
const dropdownList = document.querySelectorAll(".open-dropdown");

for (const drop of dropdowns) {
  drop.addEventListener("click", () => {
    for (const list of dropdownList) {
      list.classList.toggle("open-list");
    }
  });
}

How can I track witch dropdown is clicked? I don't want to close one with opening another, just open current one clicked.

Class open-list is just here to add display: block to my hidden list.

CodePudding user response:

const dropdowns = document.querySelectorAll(".dropdown");
const dropdownList = document.querySelectorAll(".open-dropdown");

for (const drop of dropdowns) {
  drop.addEventListener("click", (evt) => {
    evt.currentTarget.nextElementSibling.classList.toggle('open-list');
  });
}
ul {
  display: none;
}

ul.open-list {
  display: block;
}
 <div >
    <p>Open dropdown</p>         
  </div>
  <ul >
      <li>Data 1</li>
      <li>Data 2</li>
      <li>Data 3</li>
      <li>Data 4</li>
      <li>Data 5</li>
   </ul>

 <div >
    <p>Open dropdown</p>         
  </div>
  <ul >
      <li>Data 1</li>
      <li>Data 2</li>
      <li>Data 3</li>
      <li>Data 4</li>
      <li>Data 5</li>
   </ul>

 <div >
    <p>Open dropdown</p>         
  </div>
  <ul >
      <li>Data 1</li>
      <li>Data 2</li>
      <li>Data 3</li>
      <li>Data 4</li>
      <li>Data 5</li>
   </ul>

  • Related