What is the easiest way to do a clickout in jquery Where a div box hides if clicked anywhere outside it.
Clickout in jquery
18.4k Views Asked by Hussein AtThere are 7 best solutions below

I recommend use this lib https://github.com/gsantiago/jquery-clickout. It's awesome!
$('button').on('clickout', function (e) {
console.log('click outside button')
})

$('body').click(function() {
$('#box').fadeOut();
});
$('#box').click(function(e) {
e.stopPropagation();
});
This works because #box will receive the click event first if you clicked inside. Since propagation is stopped, the handler attached to body won't receive it so the box won't be closed unless you clicked outside of the box.
If you want it to hide immediately, use .hide()
I've got the stopPropagation() trick from How do I detect a click outside an element?

I know that jQuery has the "focusout" event for form elements, not sure if it could maybe be used for a

like this:
$("#thediv").show(0, function() {
var that = $(this);
$(document).bind("click", function(e) {
if($(e.target).attr("id") != that.attr("id")) {
that.hide();
$(this).unbind("click");
}
});
});
fiddle here: http://jsfiddle.net/XYbmE/3/

Bind a click function to the document itself:
$(document).click(function(){
alert('doc');
});
Then bind a function to the same event on the div itself and return false so the event will not bubble up to the document.
$('#mydiv').click(function(e){
alert('mydiv click');
return false;
}

Heres my solution
var ClickOut = {};
ClickOut.list = [];
ClickOut.Add = function(jqel, callback) {
var i = ClickOut.list.push({jqel:jqel, callback:callback});
return (i-1);
}
ClickOut.Remove = function(i) {
ClickOut.list.splice(i, 1);
}
ClickOut.Init = function() {
$('body').click(function(e) {
for(var x = 0; x < ClickOut.list.length; x++) {
if (!ClickOut.list[x].jqel.has(e.target).length) {
ClickOut.list[x].callback();
}
}
});
}
I don't like the solutions that use
stopPropagation
because often I am using event bubbling to manage various links. I don't want to have to worry that they might stop working if the box exists. My choice would look something like this:The
has
function filters the selection and returns elements only if they contain the element passed as the parameter (you can also use a selector string, but that isn't relevant here). If the click was outside the box,length
will be0
so the conditional will pass and the box will be hidden.This should be optimised by setting a boolean value for whether the box is currently visible and only doing the
has
call if it is currently visible.