Reputation: 7969
I want hide div when user click anywhere in the page but not on the div.
<head>
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function () {
$(document).not('.me').click(function () {
$('.me').hide()
})
})
</script>
</head>
<body>
<div class="me" style="width:200px; height:200px; background:#F00">
test
</div>
</body>
Upvotes: 2
Views: 215
Reputation: 130
You can use following script to achieve this..
<script type="text/javascript">
$(document).click(function (event) {
var target = $(event.target);
if (!target.parents().andSelf().is('.me')) {
$(".me").hide();
}
});
</script>
The above syntax is to check, if the parent is other than the div(here it's me
), than only hide the div.
Happy Coding :)
Upvotes: 1
Reputation: 36794
You could use stopPropagation()
:
$(function(){
$(document).click(function(){
$(".me").hide();
});
$(".me").click(function(e){
e.stopPropagation();
});
});
Check this jsFiddle
Upvotes: 2
Reputation: 41605
You can do it adding a click event to the body
or html
elements as well as preventing the propagation of the click event over your div
element:
$(function () {
//bye bye lovely div :)
$('html, body').click(function(){
$('.me').hide();
});
//let's avoid the click propagation to the body or html
$('.me').click(function(e){
e.stopPropagation();
});
});
Upvotes: 2
Reputation: 997
$(function(){
$(document).click(function(){
$('.me').hide()
})
$('.me').click(function(){
return false;
})
})
Upvotes: 0
Reputation: 40358
$(document).click(function (e)
{
var container = $(".me");
if (container.has(e.target).length === 0)
{
container.hide();
}
});
Upvotes: 2