Smash
Smash

Reputation: 513

Toggling links in menu?

How to make that the links can works only with sub-items?

<ul>
    <li><a href="item-1">Item 1</a>
        <ul>
            <li><a href="item-1-1">item 1.1</a></li>
        </ul>
    </li>

    <li><a href="item-2">Item 2</a></li>

    <li><a href="item-3">Item 3</a>
        <ul>
            <li><a href="item-3-1">item 3.1</a>
                <ul>
                    <li><a href="item-3-1-3">item 3.1.1</a></li> <li><a href="item-3-1-2">item 3.1.2</a></li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

I did a very basical example.

$('ul').on('click','a',function(){

    if ($(this).next('ul').toggle()) return false;

});

This might toggling links with sub-items and if the link hasn't them than go to location in the href, but wont work, why?

ul li ul {
    display:none;
}

actually, here is the fiddle: nested menu

Upvotes: 1

Views: 69

Answers (1)

techfoobar
techfoobar

Reputation: 66663

It is because .toggle() will never return a falsy value even if it is called on non-existent elements. This means your if condition if ($(this).next('ul').toggle()) will always pass.

Change it to:

$('ul').on('click','a',function(){
    if ($(this).next('ul').length > 0) {
        $(this).next('ul').toggle();
        return false;
    }
});

Working demo

Upvotes: 2

Related Questions