JavaScript How to close a modal by clicking outside the modal window? close modal on click outside modal,close modal click outside

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.

Answer:1

Changing your function like so should work:

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

I found it helpful to include:

$('.item-modal').click(function(e) {
  e.stopPropagation();
});
Answer:3

Add the same click listener to your overlay.

Answer:4

I'm using Cleditor http://premiumsoftware.net/cleditor/docs/GettingStarted.html. I want to get the value on keyup and insert the text into another div. cleditor comes with change() event that i'm ...

I'm using Cleditor http://premiumsoftware.net/cleditor/docs/GettingStarted.html. I want to get the value on keyup and insert the text into another div. cleditor comes with change() event that i'm ...

Browsing Hacker News and I come across http://streamjs.org/ which is an implementation of a lazy evaluated collection in Javascript. One of the examples is this: function ones() { return new ...

Browsing Hacker News and I come across http://streamjs.org/ which is an implementation of a lazy evaluated collection in Javascript. One of the examples is this: function ones() { return new ...

This is code from a book I have explaining recursion. The problem is that I don't understand the steps taken by the program: var hanoi = function(disc,src,aux,dst) { if (disc > 0) { ...

This is code from a book I have explaining recursion. The problem is that I don't understand the steps taken by the program: var hanoi = function(disc,src,aux,dst) { if (disc > 0) { ...

I'm experimenting with the HTML5 File API, and I'm needing to use a method which I don't know enough about (simply because it's hardly documented anywhere). I'm talking about the FileWriter truncate()...

I'm experimenting with the HTML5 File API, and I'm needing to use a method which I don't know enough about (simply because it's hardly documented anywhere). I'm talking about the FileWriter truncate()...