Reputation: 2897
On my WP page I have a custom menu with one of the items ("COLLECTIONS") having a sub-menu, which is hidden by default and displayed when clicking on "COLLECTIONS" through this code:
$( 'li.item_collection' ).toggle(function() {
$( 'li.item_collection .sub-menu' ).slideDown( { duration: 200, easing: 'easeInOutExpo' } );
}, function() {
$( 'li.item_collection .sub-menu' ).slideUp(100);
});
Problem is, I can't click on sub-menu items because doing so triggers the toggle() binded to "COLLECTIONS" items. How to fix that?
Upvotes: 0
Views: 44
Reputation: 58462
You need to stop the click event bubbling up the DOM tree:
$( 'li.item_collection .sub-menu' ).click(function(e) {
e.stopPropagation();
});
More info on e.stopPropagation()
I would also change your toggle code to the following so it only toggles the sub-menu of the clicked item:
$( 'li.item_collection' ).toggle(function() {
$(this).find( '.sub-menu' ).slideDown( { duration: 200, easing: 'easeInOutExpo' } );
}, function() {
$(this).find( '.sub-menu' ).slideUp(100);
});
Upvotes: 1
Reputation: 23
I would suggest using a more specific selector such as id in order to only target the highest level expandable menu. Currently your code binds to all li.item_collection which applies to the sub menu ass well. Another way would be to get the class of the clicked element and check the class does not contain sub-menu or checking the child elements of the clicked element.
the easiest would be the id selector:
<li class="item_collection" id="highLevelMenu">
......
</li>
and in that case jquery should be:
$( '#highLevelMenu' ).toggle(function() {
$( 'li.item_collection .sub-menu' ).slideDown( { duration: 200, easing: 'easeInOutExpo' } );
}, function() {
$( 'li.item_collection .sub-menu' ).slideUp(100);
});
Upvotes: 0