javascript function loses ability to toggle

32 Views Asked by At

Using this script to open 1 of multiple menus based on the target ID. The class is .dropdownDiv. The script starts by removing the "show" class from any .dropdownDiv's, then allowing the user to toggle the targeted .dropdownDiv.

The issue is, the .remove and .toggle don't appear to work together. They work individually just fine. I can toggle one div show-unshow all day long, but clicking the other buttons will not control it. I can do the reverse and have one button remove the div from another, but then the targeting button will not remove it's own div.

<script type="text/javascript">

  document.addEventListener('DOMContentLoaded', function(event) {
  var divs = document.querySelectorAll('.navButton');

  for (var i = 0; i < divs.length; i++) {
    divs[i].addEventListener('click', showDropDown);
  }
  });

 function showDropDown() {

 //un-show all dropdowns
 var containers = document.querySelectorAll('.dropdownDiv');
  for (var i = 0; i < containers.length; i++) {
  containers[i].classList.remove('show');
  }

 // show targeted dropdown only
 var d = document.getElementById(event.target.dataset.target);
 d.classList.toggle("show");
 console.log(d);
}

</script>
1

There are 1 best solutions below

0
sh.alawneh On

a trivial way to toggle something, that is using a flag and flip it each time you hit an action, so you can do something like so:

if(a)
{//something to do}
else
{// another action to do}
 a = ! a;

so, you can remove the clicked drop down instead of removing all drop down classes.