I am using this code:
$(\'body\').click(function() {
$(\'.form_wrapper\').hide();
});
$(\'.form_wrapper\').click(function(event){
event.stopPropagatio
Updated the solution to:
var mouseOverActiveElement = false;
$('.active').live('mouseenter', function(){
mouseOverActiveElement = true;
}).live('mouseleave', function(){
mouseOverActiveElement = false;
});
$("html").click(function(){
if (!mouseOverActiveElement) {
console.log('clicked outside active element');
}
});
Here's a jsfiddle I found on another thread, works with esc key also: http://jsfiddle.net/S5ftb/404
var button = $('#open')[0]
var el = $('#test')[0]
$(button).on('click', function(e) {
$(el).show()
e.stopPropagation()
})
$(document).on('click', function(e) {
if ($(e.target).closest(el).length === 0) {
$(el).hide()
}
})
$(document).on('keydown', function(e) {
if (e.keyCode === 27) {
$(el).hide()
}
})
According to the docs, .blur()
works for more than the <input>
tag. For example:
$('.form_wrapper').blur(function(){
$(this).hide();
});
You might want to check the target of the click event that fires for the body instead of relying on stopPropagation.
Something like:
$("body").click
(
function(e)
{
if(e.target.className !== "form_wrapper")
{
$(".form_wrapper").hide();
}
}
);
Also, the body element may not include the entire visual space shown in the browser. If you notice that your clicks are not registering, you may need to add the click handler for the HTML element instead.
$(document).click(function(event) {
if ( !$(event.target).hasClass('form_wrapper')) {
$(".form_wrapper").hide();
}
});
Had the same problem, came up with this easy solution. It's even working recursive:
$(document).mouseup(function(e)
{
var container = $("YOUR CONTAINER SELECTOR");
// if the target of the click isn't the container nor a descendant of the container
if (!container.is(e.target) && container.has(e.target).length === 0)
{
container.hide();
}
});