I’m trying to build a mega menu in Shopify, this is what I have in my HTML:
$('.has-child').on('click', function(event) {
event.preventDefault();
$(this).find('.child').toggleClass('menu-visible');
$('.child').click(function(e) {
e.stopPropagation();
});
});
.menu-visible{
color:red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="parent">
<li class="parent-main has-child"><a href="/collections">Shop</a>
<ul class="child">
<li class=""><a href="/collections">All Collections</a></li>
</ul>
</li>
<li class="parent-main has-child"><a href="/pages/about">About</a>
<ul class="child">
<li class=""><a href="/pages/">Child link</a></li>
<li class=""><a href="/pages/">Child link</a></li>
</ul>
</li>
</ul>
It’s working as long as I’m clicking to open and close the same parent menu but the issue I’m having is once I click on one parent menu item and then click on another parent menu item it will open the second menu on the first (so if I click on "Shop" and then click "About" it will open the "About" menu on top of the "Shop" menu). I know I need to get it to remove the "menu-visible" class once I click another parent link but I just don’t know how… I tried something with .siblings() but it didn’t work, maybe I used it wrong…
Any ideas?
-Thanks.
4
Answers
Simply first remove class from all elements then re-apply on just wanted one.
use
if ($(this).find('.child').hasClass("menu-visible")) {
in order to toggle and remove from others in same timeBasically what you need is to add the display none to all the other children and toggle the one that you are clicking, by using the not() function you can achieve this without an if statement