Use jQuery mouseup event (. mouseup()) with target property (event. target) to detect click event and hide div when clicking outside of the specific element.
To hide an element when clicked outside: Add a click event listener to the document object. On each click, check if the clicked element is outside of the specific element using the contains() method. If the clicked element is outside, hide the original element.
$(document). click(function (event) { $('#myDIV:visible'). 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();
}
});
You'd better go with something like this:
var mouse_is_inside = false;
$(document).ready(function()
{
$('.form_content').hover(function(){
mouse_is_inside=true;
}, function(){
mouse_is_inside=false;
});
$("body").mouseup(function(){
if(! mouse_is_inside) $('.form_wrapper').hide();
});
});
This code detects any click event on the page and then hides the #CONTAINER
element if and only if the element clicked was neither the #CONTAINER
element nor one of its descendants.
$(document).on('click', function (e) {
if ($(e.target).closest("#CONTAINER").length === 0) {
$("#CONTAINER").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.
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();
});
$(document).click(function(event) {
if ( !$(event.target).hasClass('form_wrapper')) {
$(".form_wrapper").hide();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With