Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
91
rated 0 times [  96] [ 5]  / answers: 1 / hits: 15731  / 8 Years ago, sun, july 10, 2016, 12:00:00

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 classother-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();
});

More From » jquery

 Answers
154

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


[#61439] Thursday, July 7, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
corie

Total Points: 371
Total Questions: 110
Total Answers: 113

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
;