Multiple drop-down menus

I am writing code for drop-down menus (https://www.theodinproject.com/courses/javascript/lessons/dynamic-user-interface-interactions?ref=lnav#drop-down-menus).

The basic logic:
In the HTML, a user puts the dropdown content under a .dropdown-content div, and this is wrapped by a .dropdown-container div.
So something like:

I have event listeners for each dropdown-container, which will toggle visibility on clicking it. And I also have a general window event listener where if one clicks outside the .dropdown-containers, it gets rid of all the drop-downs.

I however have one peculiar issue which I can’t solve. If I click on Button1 which then shows its dropdown-content, and then I click on Button 2 - it will show both dropdown-contents. How could I get it to first close the Button 1 dropdown?

Thanks!

Sorry, I think I solved it. But if anyone knows of a better way to do this than what I’ve outlined below, please do let me know! The way I have it just looks a bit ugly.

For each of the dropdown-container event listeners, I first iterate through all dropdown-container elements again, and if it’s not the one that was clicked, I make its dropdown invisible & only then do I toggle visibility for the chosen dropdown-container.

The general window.onclick event listener still works the same way, where if I click anywhere outside the dropdown-containers, it gets rid of all drop-downs.

Thanks again!

Hi, my first idea after reading the post is to use this

if you have an function/event handler doing this, you can call it inside the event handler of the dropdown-container before doing the drop-down. Probably you do it and the problem is another thing.

If you want, share the github repo (or something else). With the code is easier to give an opinion.

@fernandopaz1 Thanks! This was exactly it. Initially I wasn’t calling the general window event handler inside the dropdown-container event handler - fixing that solved the problem.

1 Like