I am using this code:
$('body').click(function() {
$('.form_wrapper').hide();
});
$('.form_wrapper').click(function(event){
event.stopPropagation();
});
And this HTML:
<div class="form_wrapper">
<a class="agree" href="javascript:;">I Agree</a>
<a class="disagree" href="javascript:;">Disagree</a>
</div>
The problem is that I have links inside the DIV and when they no longer work when clicked.
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();
}
});
Just put it in my project, but with a minor adjustment, using an array of elements to loop through them all at once. jsfiddle.net/LCB5W
@mpelzsherman Many people commented that the snippet works on touch devices but since the post has been edited these comments have somewhat vanished. TBH I don't know whether I used "mouseup" for a specific reason but if it also works with "click" I see no reason why you shouldn't use "click".
I needed that the container is hide one time with this event, this callback should be destroyed when used. To do that, i used namespace on click event with bind("click.namespace") and when the event occurred, i call unbind("click.namespace"). And finally, i used $(e.target).closest(".container").length to recognize container ... So, i did not use any trick from this answer :D
Remembering to use
$("YOUR CONTAINER SELECTOR").unbind( 'click', clickDocument );
just beside.hide()
. Sodocument
don't keep listening for clicks.For best practices I'd wrote
$(document).on("mouseup.hideDocClick", function () { ... });
in the function that opens the container, and$(document).off('.hideDocClick');
on hide function. Using namespaces I'm not removing other possiblemouseup
listeners attached to the document.