Question

I have this code:

$("a.shownav").on("click", function(){
    $("div.nav").slideToggle();
});

And when I click on the other parts of the page, except for the div.nav part, I want the div.nav part to slideup. I have tried this but it doesn't seem to work:

if ($("div.nav").is(":visible")){
    $("*").not("div.nav").on("click", function(){
        $("div.nav").slideUp();
    });
}

How do I achieve what I want?

Was it helpful?

Solution

You could handle the click event of the document, get the target object, then test if it is the nav div or a child of the nav div. If it is not one of the 2, you can close it.

$(document).on("click", function(e){
    var targ = $(e.target);
     if (!targ.hasClass("nav") && targ.parents(".nav").length < 1) {
        $("div.nav").slideUp();
    }
});

DEMO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top