Search code examples
jquerydrop-down-menuvisible

Click away from :visible div to close it


Ok, this question has been asked alot.. but i can't find any answer which fits my current project.

I am creating a drop down menu which is very similar to facebook settings dropdown.

It is fully functional except for closing when a user clicks away from the div.

I've tried a couple of things, but i can't seam to get it too work.

Here is the jquery..

$(document).ready(function(){

    $("#settings").hide();

    $("#settings_button").click(function(){
        $("#settings").toggle();

     if ($('#settings').is(":visible")){
        $('#settings_button').css({"background-Color":"darkred", "color":"red"});
        };
     if ($('#settings').is(":hidden")){
        $('#settings_button').css({"background-Color":"", "color":""});
        };
    });

});

$(document).click(function(e) {   
        if((e.target.id != 'settings_dropdown') && $('#settings_dropdown').is(":visible")) {
            $("#settings_dropdown").hide();   
        } 
});

and here is a fiddle


Solution

  • You can hide your dropdown menu systematically when a click occurs on the document, and simply stop event propagation when a click is performed on a element that doesn't hide it

    Example :

    $(document).on( "click", function( e) {  
         $( "#settings" ).hide();
    });
    
    $( "#settings" ).on( "click", function( e ) {
        e.stopPropagation();
        // Do some stuff
    });
    

    Updated fiddle