Close a div by clicking outside

I want to hide a div by clicking on the close link in it, or by clicking anywhere outside that div.

I am trying following code, it opens and close the div by clicking close link properly, but if I have problem to close it by clicking anywhere outside the div.

$(".link").click(function() {
  $(".popup").fadeIn(300);
}

);
$('.close').click(function() {
  $(".popup").fadeOut(300);
}

);
$('body').click(function() {
  if (!$(this.target).is('.popup')) {
    $(".popup").hide();
  }
}

);
<div class="box">
  <a href="#" class="link">Open</a>
  <div class="popup">
    Hello world
    <a class="close" href="#">Close</a>
  </div>
</div>

Demo: http://jsfiddle.net/LxauG/


An other way which makes then your jsfiddle less buggy (needed double click on open).

This doesn't use any delegated event to body level

Set tabindex="-1" to DIV .popup ( and for style CSS outline:0 )

DEMO

$(".link").click(function(e){
    e.preventDefault();
    $(".popup").fadeIn(300,function(){$(this).focus();});
});

$('.close').click(function() {
   $(".popup").fadeOut(300);
});
$(".popup").on('blur',function(){
    $(this).fadeOut(300);
});

You need

$('body').click(function(e) {
    if (!$(e.target).closest('.popup').length){
        $(".popup").hide();
    }
});

I'd suggest using the stopPropagation() method as shown in the modified fiddle:

Fiddle

$('body').click(function() {
    $(".popup").hide();
});

$('.popup').click(function(e) {
    e.stopPropagation();
});

That way you can hide the popup when you click on the body, without having to add an extra if, and when you click on the popup, the event doesn't bubble up to the body by going through the popup.


You'd better go with something like this. Just give an id to the div which you want to hide and make a function like this. call this function by adding onclick event on body.

function myFunction(event) { 

if(event.target.id!="target_id")
{ 
    document.getElementById("target_id").style.display="none";
  }
}

Add a transparent background taking up the whole window size, just before your popup div

.transparent-back{
    position: fixed;
    top: 0px;
    left:0px;
    width: 100%;
    height: 100%;
    background-color: rgba(255,255,255,0.5);
}

Then on its click, dismiss the popup.

$(".transparent-back").on('click',function(){
    $('popup').fadeOut(300);
});