Skip to content Skip to sidebar Skip to footer

Hide Div If Clicked Outside Of It

I’m having a little trouble with this JQuery function. Basically, I have a div, that when clicked, shows another Div. It’s set to a toggle, actually, so it toggles on/off when

Solution 1:

EDIT : A better approach here: How to create a custom modal popup - and how to close it clicking outside of it


jsBin demo
$( "#idSelect" ).click(function( e ) {
   e.stopPropagation();
   $("#idDiv").toggle();
});

$( "#idDiv" ).on('click',function( e ) {
     e.stopPropagation();
});

$( document ).on('click', function( e ) {
   if( e.target.id != 'idDiv' ){
       $( "#idDiv" ).hide();
   }   
});

Solution 2:

Hope this helps:

$(document).click(function() {
   if($(window.event.target).attr('id') != 'idSelect')
       $("#idDiv").hide();
});

Solution 3:

$(document).on("click",function(e) {
   if ($(e.target).is("#idDiv, #idDiv *"))
       $("#idDiv").show();
   else
       $("#idDiv").hide();
});

Solution 4:

jQuery-outside-events plugin adds support for the following events

clickoutside, dblclickoutside, focusoutside, bluroutside, mousemoveoutside, mousedownoutside, mouseupoutside, mouseoveroutside, mouseoutoutside, keydownoutside, keypressoutside, keyupoutside, changeoutside, selectoutside, submitoutside.

Applied to your case you can do

    $("#idDiv").on("clickoutside", function() {
        $("#idDiv").hide();
    });

    $("#idSelect").on("click", function( e ) {
        $("#idDiv").toggle();
        e.stopPropagation();
    });

Demo here

Post a Comment for "Hide Div If Clicked Outside Of It"