What is the easiest way to do a clickout in jquery Where a div box hides if clicked anywhere outside it.
To detect a click outside of an element, attach the click event handler to the area outside of the element such as the document. In the event handler check the target for the element or an element descendant by using the jQuery closest method.
So, for detecting a click outside an element, it would be best if you add a listener to the whole document element. Consequently, the main loop will go up the DOM from the clicked target element to search if the ancestor of that element belongs to the flyout container.
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:
var $box = $('#box');
$(document.body).click(function(){
if (!$box.has(this).length) { // if the click was not within $box
$box.hide();
}
});
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 be 0
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.
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