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>
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