Reputation: 31
I have a vertical sidebar nav menu with multiple buttons, each of which contains a dropdown of links. Clicking a button reveals a dropdown of anchor links in the nav menu (e.g. TF000120), and a div (e.g.'the forest') to the right of the nav menu in the main content area. Currently, if I click a button, its div and dropdown are both revealed fine. However if I click another button before closing the first, both sets of divs and dropdowns open. How would I make it so when another button is clicked, the currently open div and dropdown links are hidden again, before revealing the new div and dropdown links?
I used this tutorial on W3.
HTML (Nav Menu)
<nav class="sidenav">
<a href="#theforest" class="dropdown-btn" onclick="toggle_visibility('theforest');">The Forest
</a>
<div class="dropdown-container">
<a class="entry-num" href="#TF000120">[TF000120]</a>
<a class="entry-num" href="#TF000220">[TF000220]</a>
<a class="entry-num" href="#TF000320">[TF000320]</a>
</div>
<a href="#theocean" class="dropdown-btn" onclick="toggle_visibility('theocean');">The Ocean</a>
<div class="dropdown-container" >
<a class="entry-num" href="#TO000120">[TO000120]</a>
<a class="entry-num" href="#TO000220">[TO000220]</a>
<a class="entry-num" href="#TO000320">[TO000320]</a>
</div>
<a href="#thesky" class="dropdown-btn" onclick="toggle_visibility('thesky');">The Sky</a>
<div class="dropdown-container" >
<a class="entry-num" href="#TS000120">[TS000120]</a>
<a class="entry-num" href="#TS000220">[TS000220]</a>
<a class="entry-num" href="#TS000320">[TS000320]</a>
</div>
</nav>
JS
<script>
var dropdown = document.getElementsByClassName("dropdown-btn");
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>
<!--Toggle Function-->
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
Thanks!
Upvotes: 1
Views: 2184
Reputation: 1435
reset the style of all dropdowns on click, before you show the new one:
dropdown[i].addEventListener("click", function() {
//hide all divs that may be visible
var lst = document.getElementsByClassName("dropdown-containder");
for (var j = 0; j < lst.length; j++) { lst[j].style.display = "none";}
//show the dive that the user selected
this.classList.toggle("active");
var dropdownContent = this.nextElementSibling;
if (dropdownContent.style.display === "block") {
dropdownContent.style.display = "none";
} else {
dropdownContent.style.display = "block";
}
});
}
Upvotes: 1