Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close a modal by clicking outside the modal window?

In a very simple jQuery modal, I close the modal by clicking on CLOSE as

$('#close').click(function(e) {
  e.preventDefault();
  $('#overlay, #alertModalOuter').fadeOut(400, function() {
     $(this).remove();
  });
});

How can I close the modal by clicking whether on CLOSE button (which is inside the modal windows) OR clicking anywhere outside the modal window.

like image 585
Googlebot Avatar asked Nov 16 '11 13:11

Googlebot


2 Answers

Changing your function like so should work:

    $('#close, #overlay').click(function(e) {
      e.preventDefault();
      $('#overlay, #alertModalOuter').fadeOut(400, function() {
      $('#close').remove();
    });
});
like image 61
Rich O'Kelly Avatar answered Oct 01 '22 02:10

Rich O'Kelly


I found it helpful to include:

$('.item-modal').click(function(e) {
  e.stopPropagation();
});
like image 37
Ryan Charmley Avatar answered Oct 01 '22 02:10

Ryan Charmley