Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close div (modal) clicking outside. Pinterest and Facebook way

The classic way to is to do a modal is a div with the content (dialog) and a div with z-index lower (overlay) Then, I can bind the click event on the overlay and hide de content dialog.

<div class="dialog">...</div>
<div class="overlay" style="background-color:rgba(255, 255, 255, 0.9)">

But I have noticed that Pinterest and Facebook combines it to one div.

<div class="overlay" style="background-color:rgba(255, 255, 255, 0.9);position: fixed; z-index: 9999;top: 0;right: 0;bottom: 0;left: 0;">
      <div class="dialog" style="position: static;"></div>
</div>

But in this approach, how can I bind the click event to close de dialog only in the overlay that not have the dialog?

http://jsfiddle.net/mCupS/9/

like image 744
Luccas Avatar asked Dec 13 '22 03:12

Luccas


2 Answers

By doing something like this:

$('.modal').click(function(){
     $('.modal, .inner').hide(); 
});                                    
$('.inner').click(function(e){
   e.stopPropagation();
});              
​

http://jsfiddle.net/mCupS/10/

event.stopPropagation() : Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

like image 74
Soufiane Hassou Avatar answered May 01 '23 18:05

Soufiane Hassou


stopPropagation will stop the event propagation to parent controls and you will not get model click event:

$('.modal ').click(function(){
    alert("a");
});

$('.inner').click(function(e){
    alert("b");
    e.stopPropagation();
});

Edit, a better way to achieve the above.

There could be a better way as pointed in comments then above suggested solution as discussed in The Dangers of Stopping Event Propagation. By this way you can ensure that the inner item is not being click to hide.

Live Demo

$(document).on('click', function(event) {
  if (!$(event.target).closest('.inner').length) {
    $('.modal .inner').hide();
  }
});
like image 23
Adil Avatar answered May 01 '23 17:05

Adil