I am using this code:
$(\'body\').click(function() {
$(\'.form_wrapper\').hide();
});
$(\'.form_wrapper\').click(function(event){
event.stopPropagatio
var n = 0;
$("#container").mouseenter(function() {
n = 0;
}).mouseleave(function() {
n = 1;
});
$("html").click(function(){
if (n == 1) {
alert("clickoutside");
}
});
Return false if you click on .form_wrapper:
$('body').click(function() {
$('.form_wrapper').click(function(){
return false
});
$('.form_wrapper').hide();
});
//$('.form_wrapper').click(function(event){
// event.stopPropagation();
//});
var exclude_div = $("#ExcludedDiv");;
$(document).click(function(e){
if( !exclude_div.is( e.target ) ) // if target div is not the one you want to exclude then add the class hidden
$(".myDiv1").addClass("hidden");
});
FIDDLE
Instead of listening to every single click on the DOM to hide one specific element, you could set tabindex
to the parent <div>
and listen to the focusout
events.
Setting tabindex
will make sure that the blur
event is fired on the <div>
(normally it wouldn't).
So your HTML would look like:
<div class="form_wrapper" tabindex="0">
<a class="agree" href="javascript:;">I Agree</a>
<a class="disagree" href="javascript:;">Disagree</a>
</div>
And your JS:
$('.form_wrapper').on('focusout', function(event){
$('.form_wrapper').hide();
});
(Just adding on to prc322's answer.)
In my case I'm using this code to hide a navigation menu that appears when the user clicks an appropriate tab. I found it was useful to add an extra condition, that the target of the click outside the container is not a link.
$(document).mouseup(function (e)
{
var container = $("YOUR CONTAINER SELECTOR");
if (!$("a").is(e.target) // if the target of the click isn't a link ...
&& !container.is(e.target) // ... or the container ...
&& container.has(e.target).length === 0) // ... or a descendant of the container
{
container.hide();
}
});
This is because some of the links on my site add new content to the page. If this new content is added at the same time that the navigation menu disappears it might be disorientating for the user.
Live DEMO
Check click area is not in the targeted element or in it's child
$(document).click(function (e) {
if ($(e.target).parents(".dropdown").length === 0) {
$(".dropdown").hide();
}
});
UPDATE:
jQuery stop propagation is the best solution
Live DEMO
$(".button").click(function(e){
$(".dropdown").show();
e.stopPropagation();
});
$(".dropdown").click(function(e){
e.stopPropagation();
});
$(document).click(function(){
$(".dropdown").hide();
});