hide div if clicked outside of it [duplicate]

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 you click.

I want to have it where if you click on anywhere outside of the opened div (that appears after you click on the first div), the div that was opened is closed.

$("#idSelect").click(function() {
   $("#idDiv").toggle();
});

Answers:

Answer

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();
   }   
});

Answer

Hope this helps:

$(document).click(function() {
   if($(window.event.target).attr('id') != 'idSelect')
       $("#idDiv").hide();
});
Answer
$(document).on("click",function(e) {
   if ($(e.target).is("#idDiv, #idDiv *"))
       $("#idDiv").show();
   else
       $("#idDiv").hide();
});
Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.