Home  >  Q&A  >  body text

Title rewrite: dropdown toggle limited to selecting first value

I've made a dropdown that toggles successfully, but it only seems to select the first class, and when I click the second dropdown, it toggles the contents of the first dropdown. Am I missing something here? This is my code:

const menuListDropdown = document.querySelectorAll('.menu-block-dropdown');
const menuBlock = document.querySelector('.menu-block');

menuListDropdown.forEach((menuBlockList) => {
  menuBlockList.addEventListener('click', function() {
    menuBlock.classList.toggle('menu-block-active');
  })
})
.menu-block {
  background: #fff;
  box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 5px 0px, rgba(0, 0, 0, 0.1) 0px 0px 1px 0px;
  padding: 15px;
  border-radius: 8px;
  position: absolute;
  top: 35px;
  opacity: 0;
  transition: 150ms ease;
}

.menu-block-active {
  transition: 150ms all;
  opacity: 1;
}

.menu-block-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.menu-block-list a {
  color: #444444;
  margin: 0 0 0.25 0;
  padding: 0;
  font-weight: 500;
}
<li class="menu-block-dropdown">
  <a href="#">Resources</a>
  <div class="menu-block">
    <div class="menu-block-list">
      <a href="#">Dropdown 1</a>
      <a href="#">Dropdown 2</a>
    </div>
  </div>
</li>
<li class="menu-block-dropdown">
  <a href="#">Blogs</a>
  <div class="menu-block">
    <div class="menu-block-list">
      <a href="#">Dropdown 3</a>
      <a href="#">Dropdown 4</a>
    </div>
  </div>
</li>

P粉511749537P粉511749537235 days ago336

reply all(1)I'll reply

  • P粉141911244

    P粉1419112442024-02-27 00:56:42

    The problem is that you only selected one dropdown. So what you need to do is select the dropdown associated with the menu link you clicked.

    See below the changes I made in JS

    const menuListDropdown = document.querySelectorAll('.menu-block-dropdown');
    
    // Not needed
    // const menuBlock = document.querySelector('.menu-block');
    
    menuListDropdown.forEach((menuBlockList) => {
      menuBlockList.addEventListener('click', function() {
        // Select the Block within the Target List
        const menuBlock = menuBlockList.querySelector(".menu-block");
        menuBlock.classList.toggle('menu-block-active');
      })
    })
    .menu-block {
      background: #fff;
      box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 5px 0px, rgba(0, 0, 0, 0.1) 0px 0px 1px 0px;
      padding: 15px;
      border-radius: 8px;
      position: absolute;
      top: 35px;
      opacity: 0;
      transition: 150ms ease;
    }
    
    .menu-block-active {
      transition: 150ms all;
      opacity: 1;
    }
    
    .menu-block-list {
      display: flex;
      flex-direction: column;
      gap: 15px;
    }
    
    .menu-block-list a {
      color: #444444;
      margin: 0 0 0.25 0;
      padding: 0;
      font-weight: 500;
    }
    
    li {
      display: inline-block;
    }
    
    

    reply
    0
  • Cancelreply