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

Luccas picture Luccas · Apr 28, 2012 · Viewed 16.9k times · Source

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/

Answer

Soufiane Hassou picture Soufiane Hassou · Apr 28, 2012

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.