I have two dropdown menu buttons. I have only one function to toggle between the two dropdown menu. I need one dropdown to close when I click on the other and also display the right drop down menu for the right button(drop down one should only display drop down one menu). How should I write my logic for this?
<div class="dropdown">
<button onclick="myFunction()" >Dropdown-one</button>
<button onclick="myFunction()" >Dropdown-two</button>
<div id="myDropdown-one" class="dropdown-content">
<h1>First Drop down</h1>
</div>
<div id="myDropdown-two" class="dropdown-content">
<h1>Second Drop down</h1>
</div>
function myFunction() {
if ( ?? ?? ? ) {
document.getElementById("myDropdown-one").classList.toggle("show");
document.getElementById("myDropdown-two").classList.toggle("show");
}
}
You can achieve this by adding IDs to each button and use it when calling the function, so the function knows which button is calling it.
We add a data-for
attribute to each button, with the value set to the ID of the corresponding dropdown. And when calling the function, we pass the attribute by calling using this.getAttribute('data-for') // 'this' refers to the button.
We have a list of all dropdowns in the function. We remove the one that is clicked, show the clicked one, and hide all the rest (In this case, it's only one, but it can work for 2+ dropdowns too.)
Note that we use data-
in front of the attribute. It's not necessary, but it's common practice for not built-in attributes.
function myFunction(id) {
const dropdowns = ['myDropdown-one', 'myDropdown-two']
dropdowns.splice(dropdowns.indexOf(id), 1)
document.getElementById(id).classList.add('show')
dropdowns.forEach(dropdown => {
document.getElementById(dropdown).classList.remove('show')
})
}
.dropdown-content {
display: none;
}
.show {
display: block;
}
<button data-for="myDropdown-one" onclick="myFunction(this.getAttribute('data-for'))" >Dropdown-one</button>
<button data-for="myDropdown-two" onclick="myFunction(this.getAttribute('data-for'))" >Dropdown-two</button>
<div id="myDropdown-one" class="dropdown-content">
<h1>First Drop down</h1>
</div>
<div id="myDropdown-two" class="dropdown-content">
<h1>Second Drop down</h1>
</div>