Hide the menu, clicking on something other than the menu

advertisements

I have a menu that appears when I click an icon. Currently I can close it by clicking the 'close' icon, but I would like to be able to close it by clicking anywhere outside of the menu, when the menu is visible.

Here is a jsFiddle: http://jsfiddle.net/budapesti/3v5ym2bp/3/

For example the following doesn't work:

$(document).click(function() {
        if($('.menu').is(":visible")) {
            $('.menu').hide()
        }
});

I found similar questions, such as jQuery: Hide element on click anywhere else apart of the element and How do I detect a click outside an element?, but couldn't get the solutions to work for me.


EDIT: I wonder if is(":visible") works with jQuery "animate"?


Use css attribute left to detect if the menu is visible instead of :visibe because it's bot work with chrome, see jquery .is(“:visible”) not working in Chrome.

You have just to detect if the menu is visible (use the css attribute left) because if the menu css left=0px that mean it's visible, and after that if the click is outside of menu or not and so if outside close it.

Take a look at Your updating fiddle work fine just by adding the following handle that detect outside click :

JS :

$(document).click(function(e) {
    //if the menu is visible
    if($(".menu").css('left') =="0px"){
        //if the click is outside of menu
        if($(e.target).closest('.menu').length == 0){
            $('.closed').click();
        }
    }
});