Search code examples
jquerydrop-down-menupreventdefault

preventDefault() with drop-down-menu + prevDef disable after second click - explanation?


Thanks to MjrKusanagi we replace preventDefault with return false.

Also thanks to him we refactored the code to smaller size.

HTML

<ul id="menu-top-menu">
    <li>
        <a href="http://stackoverflow.com">1 level</a>
        <ul>
            <li><a href="http://stackoverflow.com"> 2 level</a>
                <ul>
                <li><a href="http://stackoverflow.com">3 level</a></li>
                </ul>
           </li>
        </ul>
    </li>
    <li>
        <a href="http://stackoverflow.com">1 level</a>
        <ul>
            <li><a href="http://stackoverflow.com">2 level</a></li>
        </ul>
    </li>
</ul>

as You see normal nested menu

jQuery

$('#menu-top-menu li').click(function(event) {
if($(this).children('ul').is(':visible')) return true;
if($(this).children().is('a:last-child')) return true;
if($(this).siblings().is(":visible")) $(this).siblings().children("ul").hide("fast");
$(this).children('ul').toggle("slow");
return false;

Code works great. You can easily implement it to any drop-down-menu ;) Thank You MjrKusanagi !!!

http://jsfiddle.net/NLKmb/20/


Solution

  • I think you can replace all the code you had in the JSFiddle with the following:

    $('#menu-top-menu li').click(function(ev) {
        if($(this).children('ul').is(':visible'))
            return true;
        if($(this).children('ul').toggle("slow").length)
            return false;
        ev.stopPropagation();
    });