简体   繁体   中英

Dropdown links using jQuery .slidetoggle

I'm using the following code to create a dropdown menu using .slidetoggle and jQuery:

<ul>
    <li class="expand"><span>Dropdown</span>
        <ul class="sub-menu">
            <li style="display: none;"><a href="http://google.com">Foo</a></li>
            <li style="display: none;"><a href="http://google.com">Foo</a></li>
            <li style="display: none;"><a href="http://google.com">Foo</a></li>
        </ul>
    </li>
</ul>

It works fine and clicking li.expand reveals/hides the child li's.

The problem is that when a link is clicked (eg google.com), on most browsers the menu first toggles ul.sub-menu up before activating the link.

How do I stop the menu from toggling up when a link is clicked?

For clarification the above code works as required on Safari.

JSFiddle example if needed: https://jsfiddle.net/fcs5n8o6/3/

Add this:

$('.sub-menu').find('a').click(function(event){
     event.stopPropagation();                          
});

According to event.stopPropagation method clicked links will not notify li elements about clicks (they do it now), and click handler for li will not fire.

Updated jsfiddle

There is even better and concise solution:

<ul>
    <li class="expand"><span>Dropdown</span>
        <ul class="sub-menu" style="display: none;">
            <li><a href="http://google.com">Foo</a></li>
            <li><a href="http://google.com">Foo</a></li>
            <li><a href="http://google.com">Foo</a></li>
        </ul>
    </li>
</ul>

<script>
    $(".expand").click(function() {
        $(".sub-menu").slideToggle("slow");
        $('.sub-menu').find('li').click(function(event){
             event.stopPropagation();                          
        });
    });
</script>

new jsfiddle

I also edited jQuery selectors, they were a little bit too exuberant and not very effective.

As for your site: find file custom.js?ver=1 line 405:

$(".leftnav ul li.removelink.driver").click(function() {
    event.stopPropagation();
    $(".leftnav ul li.removelink.driver li").slideToggle("slow");
});

change for this:

$(".leftnav ul li.removelink.driver").click(function() {

        $(".leftnav ul li.removelink.driver li").slideToggle("slow")
        .click(function(event){event.stopPropagation();});

    });

I think you need event.stopPropagation();

https://jsfiddle.net/zer00ne/yoggar2z/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM