I am trying to create a drop down menu in Javascript and would like to display the elements of each UL when a user clicks on the first child.
here is the code i am using to hide/show the UL children
<div class="menu_wrapper">
<ul class="menu_company">
<li class="main_item company">Our Company</li>
<li class="menu_item hide_menu">About US</li>
<li class="menu_item hide_menu">Our offices</li>
<li class="menu_item hide_menu">Careers</li>
</ul>
<ul class="products">
<li class="main_item products">Our Products</li>
<li class="menu_item hide_menu">Product A</li>
<li class="menu_item hide_menu">Product B</li>
<li class="menu_item hide_menu">Communication</li>
</ul>
</div>
Here is the function i am using to manage the display/hide of the Ul elements
const hideMenus = document.querySelectorAll('.hide_menu')
const manageMenu = (() => {
const displayMenus = () => {
hideMenus.forEach((menu) => {
menu.classList.toggle('hide_menu')
})
}
})()
and here is how i am creating the eventListener
const mainItem = document.querySelector('.main_item')
mainItem.addEventListener('click', () => {
manageMenu.displayMenus()
})
However, when i click on "Our company" or "Our products", all the elements under our company and Products are displayed.
What’s the best way to make the dropdown display elements of the clicked UL only (in JS and not jQuery)?
Thanks
2
Answers
If you’re trying to create a dropdown menu with multiple options, where only the selected option’s submenu is displayed, you can try the following code snippet.
This code uses the
querySelectorAll()
method to select all dropdown elements, and then attaches a click event listener to each button element inside a dropdown. When a button is clicked, the corresponding dropdown list is toggled to show or hide using theclassList.toggle()
method. You can also modify the HTML structure to fit your design needs, as long as you keep the class names and the event listener logic intact.I hope this helps! Let me know if you have any questions.
You’re toggling the
hide_menu
class for all of the items in your code, so that’s why both menus are shown. You need to target theul
you clicked on and only show the items inside it. Something like this should work:Here the CSS is doing a bit more of the heavy lifting, so you only need to change the class of 1 element instead of hiding each menu item separately. This also takes care of hiding the menu when clicking on the
.main_item
element of an already opened menu, which I’m assuming you would want (if not, just ignore menus that are already open). Depending on your application, you might also want to hide any other menus that are currently open, but I’ll leave that as an exercise if it’s a requirement 😊