Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 248
user1355300 Avatar asked Jul 31 '13 08:07

user1355300


People also ask

How do you hide a div when the user clicks outside of it using jQuery?

Use jQuery mouseup event (. mouseup()) with target property (event. target) to detect click event and hide div when clicking outside of the specific element.

How do you close a div in JavaScript?

To hide a div using JavaScript, get reference to the div element, and assign value of "none" to the element. style. display property.

How do I detect a click outside an element?

So, for detecting a click outside an element, it would be best if you add a listener to the whole document element. Consequently, the main loop will go up the DOM from the clicked target element to search if the ancestor of that element belongs to the flyout container.


3 Answers

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);
});
like image 133
A. Wolff Avatar answered Oct 22 '22 02:10

A. Wolff


You need

$('body').click(function(e) {
    if (!$(e.target).closest('.popup').length){
        $(".popup").hide();
    }
});
like image 38
Arun P Johny Avatar answered Oct 22 '22 03:10

Arun P Johny


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.

like image 23
Jonas Grumann Avatar answered Oct 22 '22 01:10

Jonas Grumann