Ali
Ali

Reputation: 267059

Detecting when a user clicks outside a div

I'm showing the user a modal/lightbox. The modal shows up and the rest of the page goes dim when the user clicks a button. Usual stuff.

However I want to do this. If the user clicks any element outside of the modal, I want the modal to go away and the page to return to normal.

How can this be done? I know I can set an onclick event for body, and then check if event target is my modal, but what if the user clicks on a link/textbox/button within the modal? In that case, target won't be the modal. How can I solve this?

Is there a way to check if the event target is contained with <div id="modal"></div>, so if it is, I won't close the modal, and if not, that means user clicked outside the modal and I can close it?

Upvotes: 3

Views: 1095

Answers (4)

iimos
iimos

Reputation: 5037

Another one approach:

var mouseOverModal = false;

$(document).click(function(e){
   if ( ! mouseOverModal ){
       // close modal
   }
});

$('#modal').bind("mouseenter mouseleave", function(e){
     mouseOverModal = ( "mouseenter" == e.type );
})

$('#open-modal-handler').click(function(){  
    // open modal  
    return false; // <- IMPORTANT
})

Upvotes: 1

iimos
iimos

Reputation: 5037

$("body").click(function(e){
    if( ! $(e.target).closest("#modal").length ){
        $('#modal').hide();
    }
});

demo

Upvotes: 1

Roko C. Buljan
Roko C. Buljan

Reputation: 206048

jsBin demo

$(document).mouseup(function(e){
   if(e.target.id !== 'modal' ){
     $('#modal').hide();
   }
});

$('#modal').mouseup(function(e){
  e.stopPropagation();  // prevent mouseup propagate to underneath layers
});

Upvotes: 3

Arnaud
Arnaud

Reputation: 410

You could put a div under the modal that fills the entire space and attach your click handler to it.

Upvotes: 1

Related Questions