patkay
patkay

Reputation: 121

preventDefault but activate links

In my navigation menu, I have a dropdown that I want to use. The actual dropping down is fine, and I've prevented the automatic bubbling by using preventDefault(); but now all the links within the dropdown no longer work.

How do I make it so that the dropdown works, doesn't bubble and all the links within the dropdown work?

Edit: I've also used event.stopPropagation() to no effect either. What's going on here?!

This is my code:

// Toggle dropdowns
$('.menu-item-has-children').click(function(e){
    e.preventDefault();
    $(this).find('.sub-menu').toggleClass('open');
});

Upvotes: 1

Views: 700

Answers (2)

Oriol
Oriol

Reputation: 287980

To stop bubbling, use event.stopPropagation().

Only use event.preventDefault() to prevent the default action of the event from happening.


Ah, now I see your problem. The issue is that when clicking a menu item to open a submenu, since the item is an anchor pointing to #, the document will scroll to top.

To avoid that, I suggest getting rid of href="#".

Alternatively, you can use preventDefault only if the clicked element was that element, not a descendant:

$('.menu-item-has-children').on('click', function(e){
    if(this == e.target) e.stopPropagation();
    // ...
});

Demo

Upvotes: 3

AdamP.
AdamP.

Reputation: 137

You can check which element was clicked by using e.target, and if the clicked element was a sub menu link, don't preventDefault

Upvotes: 0

Related Questions