I just wanted to ask you if it is possible to limit the amount of Dropdownmenus opened at the same time. In the following you can see the code of my dropdownmenu. I want to include a funtion that limits the amount of dropdownmenus opened to 1. So if no menu is opened it should just open normal and if a menu is already open it should close this one and open the selected one.
<script>
var dropdown = document.getElementsByClassName("dropdownbtn");
var i;
for (i = 0; i < dropdown.length; i++) {
dropdown[i].addEventListener("click", function() {
this.classList.toggle("active");
var dropdownContent = this.nextElementSibling;
if (dropdownContent.style.display === "block") {
dropdownContent.style.display = "none";
} else {
dropdownContent.style.display = "block";
}
});
}
</script>
Thanks in advance.
Your ".dropdownbtn" in place makes it more complicated. What do you think of customization?
<nav>
<ul class="my-nav">
<li>
<details class="dropdownbtn">
<summary>First</summary>
<ul>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
</ul>
</details>
</li>
<li>
<details class="dropdownbtn">
<summary>Second</summary>
<ul>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
</ul>
</details>
</li>
</ul>
</nav>
And than your logic:
var nav = document.querySelector('.my-nav');
nav.addEventListener('toggle', (event) => {
// Only run if the dropdown is open
if(!event.target.open) {
return;
}
// Get all other open dropdowns and close them
var dropdowns = nav.querySelectorAll('.dropdownbtn[open]');
Array.prototype.forEach.call(dropdowns, (dropdown) => {
if(dropdown === event.target) {
return;
}
dropdown.removeAttribute('open');
});
}, true);
I have this solution for you on codepen.