I have a dropdown menu. On some pages, the link just scrolls to the anchor instead of refreshing the page. When this happens then dropdown menu is supposed to close. But it does not.
This is my html
<div class="navbar">
<div class="nav_item">
<div class="dropdown menu_item" >
<span class="navbar-submenu"> <a href="/">dropdown</a></span>
<div class="secondarynav" >
<div class="nav_item">
<div class="menu_item" >
<a href="/#">link</a>
</div>
</div>
<div class="nav_item">
<div class="menu_item" >
<a href="/#">link</a>
</div>
</div>
</div>
</div>
</div>
<div class="nav_item">
<div class="menu_item" >
<a href="/">link</a>
</div>
</div>
</div>
What is supposed to happen is when a visitor clicks on dropdown, active class is added to the parent nav_item, which then shows the rest of the menu. When a user clicks dropdown again active is removed and dropdown closes.
$('.dropdown').click(function (e) {
$(this).closest('.nav_item').toggleClass('active');
});
Now the problem, when a visitor clicks dropdown, then any of the children links I would like the active class removed, which currently only happens when the dropdown link is clicked.
I have tried various other methods
$('.nav_item.active > *').click(function(e) {
$(this).closest('.active').removeClass('active');
});
But this glitches with the toggle function in the other scipt. Basically the active is added then removed straight away.
How can I set it so when .dropdown is clicked .active is added to the parent nav_item. But then if any link in that menu is clicked the .active is removed? Thanks
Use e.stopPropagation() to prevent the event on the item from bubbling up to the dropdown.
$('.nav_item.active > *').click(function(e) {
e.stopPropagation();
$(this).closest('.active').removeClass('active');
});