I'm creating a dropdown nav for mobile and I'm using an active class to hide and show submenus via CSS. The code below works for the initial list item, but closes the parent as soon I try and open a child list item in the submenu (which uses the same structure and classes)
What I think is happening
I think the issue is that as soon as I click inside the parent li the js registers the click event and closes via the toggle.
Problem
So how do I get the javascript to select the child link and attach the click event to that, but still add the active class to the parent li item so the CSS cascades through the submenus?
HTML:
<ul>
<li class="menu-item-has-children nav-level-0">
<a class="#">Child link</a>
<ul class="submenu"></ul>
</li>
<li class="menu-item-has-children nav-level-0">
<a class="#">Child link</a>
<ul class="submenu"></ul>
</li>
</ul>
Javascript:
var nav_link = document.querySelectorAll(".menu-item-has-children");
for (var i = 0; i < nav_link.length; i++) {
nav_link[i].addEventListener("click", function() {
this.classList.toggle('active');
});
}
So how do I get the javascript to select the child link and attach the click event to that, but still add the active class to the parent
liitem so the CSS cascades through the submenus?
Try this
var nav_link = document.querySelectorAll(".menu-item-has-children");
for (var i = 0; i < nav_link.length; i++) {
nav_link[i].querySelector('a').addEventListener("click", function () {
this.parentElement.classList.toggle('active');
});
}
I am writing this as crude solution. Maybe you can implement this using a foreach. However the issue you are facing is because of event bubbling. You need to stop the click done on sub-menu to propogate to the parent (which is triggering the toggle of active class, therefore, hiding the element.
Add this to your javascript
var submenu = document.querySelectorAll(".submenu");
for (var i = 0; i < submenu.length; i++) {
submenu[i].addEventListener("click", function(event) {
event.stopPropagation()
});
}
This solution however, doesn't add/remove active class to submenu, in case you have to expand that. I suggest using a common selector class for doing that