Search code examples
jqueryslidedownslideup

Jquery: Click slideUp Issue


I have a JQuery navigation which on clicking a parent <li> slides down using JQuery. On a second click it will slide the navigation up. The problem I have is that my clients wants it also to slide back up if he clicks somewhere else on screen, i.e just clicking on blank white space would collapse the nav.

Any ideas?

Here is the Jquery:

$('#menu-flag-menu > li > a').click(function(e) {e.preventDefault();});


$("#menu-flag-menu li a").click(function(){ 

    // close all opened sub menus
    $("ul", $(this).parent().siblings()).stop(true,true).slideUp();

    var ul = $(this).next("ul");     
    ul.stop(true,true).slideToggle('fast'); 
});

Solution

  • This should work:

    $(document).click(function (e) {
    
        // if we click on anything other than the navigation menu
        // or it's descendants then slide up the menu
        if(e.target.id !== "menu-flag-menu" 
            && !$(e.target).closest("#menu-flag-menu").length) {
            $(".sub-menu").stop().slideUp();
        }
    });