I have a vertical menu with some dropdown. Actually more dropdowns can't be opened simultaneously, and, if a dropdown is open, when I click on another dropdown-button, the dropdown closes himself.
You can see a demo here.
The problem is that now, if I click twice on the same dropdown button, the first time I click the dropdown open itself (as it should be), but the second time the dropdown doesn't close itself as I want.
Furthermore, also when the dropdown is open and I click on another button on the menu the dropdown doesn't close itself.
Here you can see my code:
<div class="sidenav">
<a href="#about">About</a>
<a href="#services">Services</a>
<a href="#clients">Clients</a>
<a href="#contact">Contact</a>
<button class="dropdown-btn">Dropdown
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-container">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
<button class="dropdown-btn">Dropdown
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-container">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
<a href="#contact">Search</a>
</div>
var accItem = document.getElementsByClassName('dropdown-container');
var accHD = document.getElementsByClassName('dropdown-btn');
for (i = 0; i < accHD.length; i++) {
accHD[i].addEventListener('click', toggleItem, false);
}
function toggleItem() {
var itemClass = this.nextElementSibling;
for (i = 0; i < accItem.length; i++) {
accItem[i].style.display = "none";
accHD[i].classList.remove("active");
}
if (itemClass.style.display === "none") {
this.classList.add("active");
//this.classList.toggle("active");
this.nextElementSibling.style.display = "block";
}
}
Is someone able to find where the problem is and solve it?
Thank you, regards
(Hope it is clear, if not, let me know in the comments. I do not speak English very well.)
Above your for loop try adding:
if (itemClass.style.display === "block") {
this.nextElementSibling.style.display = "none";
this.classList.remove("active");
return;
}
This will check to see if the item clicked is already open and handle setting all your values. By adding the return it will prevent the rest of the code from being executed.
Here is a fiddle with your code and answering your other question about closing them on click of one of the main links: