-1

I have a dropdown menu working but I can't figure out how to close the previous menu onclick. All the menues stay open so I need them to close when a different menu is open.

Please see my jsfiddle https://jsfiddle.net/yvhnphp4/

$(document).ready(function(){
  // Dropdown menu
  var findDropdowns = document.querySelectorAll(".has-dropdown");
  for(var i = 0; i < findDropdowns.length; i++) {
    if(i == 0) {
        var dropdownId = "has-dropdown-1";
        findDropdowns[i].setAttribute("id", dropdownId);
    }else {
        var addOneToIndex = i + 1;
        dropdownId = "has-dropdown-" + addOneToIndex;
        findDropdowns[i].setAttribute("id", dropdownId);
    }
    var targetDropdown = document.getElementById(dropdownId);
    targetDropdown.onclick = dropdownTrigger;

  }
function dropdownTrigger(e) {
    e.preventDefault();
    var showHideDropdown = e.target.nextElementSibling;

    showHideDropdown.setAttribute("class", "show");
}
});

<ul class="nav">
 <li><a class="has-dropdown" href="">Link</a>
                        <ul>
                            <li><a href="">Sub-Link</a></li>
                            <li><a href="">Sub-Link</a></li>
                            <li><a href="">Sub-Link</a></li>
                        </ul>
                    </li>
                    <li><a class="has-dropdown" href="">Link</a>
                        <ul>
                            <li><a href="">Sub-Link</a></li>
                            <li><a href="">Sub-Link</a></li>
                            <li><a href="">Sub-Link</a></li>
                        </ul>
                    </li>
                </ul>

.nav ul {display:none;}
.nav ul.show{display:block;}
Steven G
  • 7
  • 2

1 Answers1

0

You can simply remove the .show class from all ul tags in .nav that still have it, before opening a new dropdown:

function dropdownTrigger(e) {
    var opened = document.querySelectorAll(".nav ul.show");
    for(var i = 0; i < opened.length; i++) {
        opened[i].removeAttribute("class");
    }

    ...
}

Note that since you're using jQuery anyway ($(document).ready) there is probably a much better way to do this.

Also, use href="#" instead of href="".

Community
  • 1
  • 1
Lynn
  • 10,425
  • 43
  • 75