Is there any event that can be called whenever the user clicks outside the div to hide that div?
I tried using $(document).click()
, however that one is called even when the user clicks the link which is supposed to show the div. Hence, the click handler event shows the div, and immediately $(document).click()
hides it, which means the div is never displayed.
Ideas?
Is there any event that can be called whenever the user clicks outside the div to hide that div?
I tried using $(document).click()
, however that one is called even when the user clicks the link which is supposed to show the div. Hence, the click handler event shows the div, and immediately $(document).click()
hides it, which means the div is never displayed.
Ideas?
Share Improve this question edited Apr 15, 2011 at 23:08 Ali asked Apr 15, 2011 at 23:02 AliAli 267k269 gold badges592 silver badges786 bronze badges5 Answers
Reset to default 6You can try delegating the onclick event handler to the body element (or other suitable parent container) and test for whether the target element is the reveal link:
$("body").click(function(e) {
if(e.target.id == "idOfLinkToShowDiv") {
$("#idOfTheDiv").show();
} else {
$("#idOfTheDiv").hide();
}
});
The above can be shortened using .toggle
:
$("body").click(function(e) {
$("#idOfTheDiv").toggle(e.target.id == "idOfLinkToShowDiv");
});
Another way:
$("body").click(function() {
$("#idOfTheDiv").hide();
});
$(".showLink").click(function(e) {
e.stopPropagation();
$("#idOfTheDiv").show();
});
When any element is clicked, check if the ID of the element matches the one you want to hide. If it doesn't, hide it.
$("*").click(function(){
if(this.id === "hideMe"){
return false;
}
else{
$("#hideMe").hide();
}
});
Check out demo on jsFiddle
Yes. After you display the div, only then bind the click event to hide the div (to the document body). Then, on the displayed div itself, catch click() event, and prevent propagation on div click(). Any click outside the div will hide, and any click inside will not bubble to the document.
function hideDiv(){
$('#someDiv').hide();
$(document.body).unbind('click',hideDiv);
}
$('#someLink').click(function(){
$('#someDiv').show().click(function(e){ e.stopPropagation(); });
$(document.body).bind('click',hideDiv);
});
One soluation is the check which element is clicked.
Another solution might be:
<body>
<div class="infopane"></div>
<div class="wrapper">
content of page
</div>
</body>
So I can do:
$('.wrapper').click(function() {
$('.infopane').hide();
});
You are looking for the outside events plugin. Super easy to use
http://benalman./projects/jquery-outside-events-plugin/
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745182607a4615488.html
评论列表(0条)