Beppe Beppe - 3 months ago 8x
jQuery Question

Close overlay by clicking on background

I'm trying to close an overlay window by clicking on the outer body only.
The problem is that the overlay get closed even if I click on the overlay panel itself and if I click on any other element i put in it (divs, buttons, icons etc etc...)
I don't know how to target only the body around the overlay and not the overlay window itself.
Can you please help?

Here is both html markup and related JS.

<div id="main">
<div class"other-content">
<!-- other content -->
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal__content">
<!-- some content - divs, buttons etc etc -->

$(document).on('click',"#myModal", function(e) {


Use a click event on <body>, with event.currentTarget to check for elements.

$('body').on('click',function(e) {
     var $currEl = $(e.currentTarget);
     if(!$'#myModal') && !$currEl.closest('#myModal').length){
     else if(/write code element which triggers modal open even/){
        $('#myModal').fadeIn(); //or any code to trigger modal open 
  1. $'#myModal') checks if the current clicked elements is myModal
  2. $currEl.closest('#myModal').length checks if the current element in inside/child of myModal