javascript - JS Dropdown Menu Behavior -
i have dropdown menu working can't figure out how close previous menu onclick. menues stay open need them close when different menu open.
please see jsfiddle https://jsfiddle.net/yvhnphp4/
$(document).ready(function(){ // dropdown menu var finddropdowns = document.queryselectorall(".has-dropdown"); for(var = 0; < finddropdowns.length; i++) { if(i == 0) { var dropdownid = "has-dropdown-1"; finddropdowns[i].setattribute("id", dropdownid); }else { var addonetoindex = + 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;}
you can remove .show
class ul
tags in .nav
still have it, before opening new dropdown:
function dropdowntrigger(e) { var opened = document.queryselectorall(".nav ul.show"); for(var = 0; < opened.length; i++) { opened[i].removeattribute("class"); } ... }
note since you're using jquery anyway ($(document).ready
) there much better way this.
Comments
Post a Comment