Adam
Adam

Reputation: 1459

Remove link on parent li only with jQuery

I have created the following code where the nested ul shows and hides with jQuery when you click on the parent li.

The problem is this markup is generated dynamically, and I would like to disable the anchor links on the parent links only, and then have the links in the nested ul list be active.

I have tried return false, but this disables all the links. How can I just disable the parent li's?

Also the menu should not expand/collapse when the child li's are clicked.

I have the following markup....

<nav class="shop-cat">
<ul id="menu-shop-categories" class="menu">
    <li><a href="">Clothing</a>
        <ul class="sub-menu">
            <li><a href="">T-Shirts</a></li>
            <li><a href="">Sweatshirts</a></li>
            <li><a href="">Hoodies</a></li>
        </ul>
    </li>
    <li><a href="">Art</a>
        <ul class="sub-menu">
            <li><a href="">Canvas</a></li>
            <li><a href="">Prints</a></li>
        </ul>
    </li>
    <li><a href="">Accessories</a>
        <ul class="sub-menu">
            <li><a href="">Glasses</a></li>
            <li><a href="">Keyrings</a></li>
        </ul>
    </li>
</ul>
</nav>

With this jQuery...

$('#menu-shop-categories > li').click(function() {
    $(this).find('.sub-menu').slideToggle(400);
    return false;     
});

Here is a codepen also... http://codepen.io/anon/pen/ieIhC

Upvotes: 0

Views: 1064

Answers (1)

PSL
PSL

Reputation: 123739

Set the click on anchor instead of li

$('#menu-shop-categories > li > a').click(function(e) {
    e.preventDefault();
    $(this).siblings('.sub-menu').slideToggle(400);

});

Demo

Upvotes: 2

Related Questions