Thursday, June 27, 2019

javascript - 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();
}
}

);


Open






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



Answer



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);
});


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...