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/
Use jQuery mouseup event (. mouseup()) with target property (event. target) to detect click event and hide div when clicking outside of the specific element.
To hide a div using JavaScript, get reference to the div element, and assign value of "none" to the element. style. display property.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With