Beppe Beppe - 4 months ago 18
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 -->
</div>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal__content">
<!-- some content - divs, buttons etc etc -->
</div>
</div>
</div>


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

Answer

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

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