Reputation: 21
I'm having an issue trying to get the sub menus to work as I'd like. Here is my list of requirements (and what I've got so far):
So the issue right now is when you click to open a sub menu, if you click the same parent anchor it won't close. The other functionality works fine though.
JS
$('.menu-item-has-children > a').click(function () {
if ($(this).hasClass("show")) {
$('.sub-menu').removeClass('show');
} else {
$('.sub-menu').removeClass('show');
$(this).next('ul').toggleClass('show');
}
});
HTML
<ul id="menu-menu-1" class="menu">
<li><a href="#">Home</a></li>
<li class="menu-item-has-children"><a href="#">Our Advantage</a>
<ul class="sub-menu">
<li><a href="#">Why Choose Us</a></li>
<li><a href="#">Affordability</a></li>
<li><a href="#">Blah Blah Blah</a></li>
<li><a href="#">Advanced Technology</a></li>
</ul>
</li>
<li class="menu-item-has-children"><a href="#">Contact</a>
<ul class="sub-menu">
<li><a href="#">Contact Us</a></li>
<li><a href="#">Blah Blah Blah</a></li>
<li><a href="#">Appointments</a></li>
</ul>
</li>
</ul>
CSS
#menu-menu-1 li.menu-item-has-children ul {
position: absolute;
z-index: -1;
transform: translateY(-100%);
opacity: 0;
transition: all .3s ease;
}
#menu-menu-1 li.menu-item-has-children ul.show {
position: relative;
z-index: 1;
transform: translateY(0);
opacity: 1;
transition: all .3s ease;
}
I appreciate your help!
Upvotes: 0
Views: 2491
Reputation: 125
You need to check the A-Elemets children in your if-statement ( not the element itself where the listener is registered):
JS
$('.menu-item-has-children > a').click(function () {
if ($(this).next('ul').hasClass("show")) {
$('.sub-menu').removeClass('show');
} else {
$('.sub-menu').removeClass('show');
$(this).next('ul').toggleClass('show');
}
});
Upvotes: 1