2

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();
});
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
Ramesh
  • 1,829
  • 2
  • 25
  • 30

4 Answers4

6

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

Community
  • 1
  • 1
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
1

Hope this helps:

$(document).click(function() {
   if($(window.event.target).attr('id') != 'idSelect')
       $("#idDiv").hide();
});
Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57
1
$(document).on("click",function(e) {
   if ($(e.target).is("#idDiv, #idDiv *"))
       $("#idDiv").show();
   else
       $("#idDiv").hide();
});
Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
1

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

Bruno
  • 5,772
  • 1
  • 26
  • 43