Is there a way to make the submenu disappear when clicked outside of it?
I want only one menu to be open at a time.
This is my JavaScript code:
function toggleMenu() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(e) {
if (!e.target.matches('dropdown-btn')) {
var dropdowns = document.getElementsByClassName("dropdown-btn");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
This is my HTML code:
<div class="dropdown-menu">
<button class="dropdown-btn">Dropdown <i class="fa fa-caret-right"></i></button>
<div class="dropdown-container">
<button class="dropdown-btn">Dropdown<i class="fa fa-caret-right"></i></button>
<div class="dropdown-container">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
I apologize for not being able to include the full code. These are the sections where I need to implement the function on.