Search code examples
jquerypreventdefault

disabling click for main menu items not submenu jquery


HTML

<ul id="nav">
    <li>
        <a href="#">Home</a>
    </li>

    <li>
        <a href="#">About</a>
        <ul>
            <li><a href="#">The product</a></li>

            <li><a href="#">Meet the team</a></li>
        </ul>
    </li>
    <li>
        <a href="#">Services</a>

        <ul>
            <li><a href="#">Sevice one</a></li>
            <li><a href="#">Sevice two</a></li>

            <li><a href="#">Sevice three</a></li>
            <li><a href="#">Sevice four</a></li>
        </ul>

    </li>
    <li>
        <a href="#">Product</a>
        <ul>
            <li><a href="#">Small product (one)</a></li>

            <li><a href="#">Small product (two)</a></li>
            <li><a href="#">Small product (three)</a></li>
            <li><a href="#">Small product (four)</a></li>

            <li><a href="#">Big product (five)</a></li>
            <li><a href="#">Big product (six)</a></li>
            <li><a href="#">Big product (seven)</a></li>

            <li><a href="#">Big product (eight)</a></li>
            <li><a href="#">Enourmous product (nine)</a></li>
            <li><a href="#">Enourmous product (ten)</a></li>

            <li><a href="#">Enourmous product (eleven)</a></li>
        </ul>
    </li>
    <li>
        <a href="#">Contact</a>

        <ul>
            <li><a href="#">Out-of-hours</a></li>
            <li><a href="#">Directions</a></li>

        </ul>
    </li>
</ul>

jQuery

$('#nav li a').click(function(e){
    e.preventDefault();
});

Trying to disable clicking on main menu items such as About, Services etc where they have a drop down. Using the above code it just disables all my links.


Solution

  • Give your top level links the class not-clickable and add this script:

    $('.not-clickable').click(function(e){
        e.preventDefault();
    });
    

    If you have a dynamic menu, try to determine if there is a submenu, if it exists add the class to your top level element.

    edit: By using a .not-clickable class you are also better off for the future. If #nav li ever becomes #nav2 li you need to change your javascript too.