I’m facing an issue with my dropdown menu. Clicking on a button should toggle the dropdown menu, showing it if closed and hiding it if open. However, the dropdown menu does not close when I click the button again. I suspect the problem lies with the closeAll function, which is necessary to close another dropdown menu when the first one is open.
/* Toggle between hiding and showing dropdown content when button is clicked */
function myFunction() {
closeAll();
document.getElementById("myDropdown").classList.toggle("show");
}
function myFunction2() {
closeAll();
document.getElementById("myDropdown2").classList.toggle("show");
}
function closeAll(){
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
openDropdown.classList.remove('show');
}
}
// Close dropdown menu when user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
/* Dropdown Button */
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
/* Dropdown button on hover & focus */
.dropbtn:hover, .dropbtn:focus {
background-color: #3e8e41;
}
/* The container <div> - needed to position the dropdown content */
.dropdown {
position: relative;
display: inline-block;
}
/* Dropdown Content (Hidden by Default) */
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 150px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
/* Links inside the dropdown */
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
/* Change color of dropdown links on hover */
#myDropdown a:hover {background-color: #f1f1f1}
/* Show the dropdown menu (use JS to add this class to the .dropdown-content
container when the user clicks on the dropdown button) */
.show {display:block;}
#myDropdown2{
min-width:200px;
border:4px solid red;
}
#myDropdown2 a:hover{
color:red;
}
.left-bar{
float:left;
}
.right-bar{
float:left;
}
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
<div class="dropdown">
<button onclick="myFunction2()" class="dropbtn">Dropdown</button>
<div id="myDropdown2" class="dropdown-content">
<div class="left-bar">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
<div class="right-bar">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
</div>