jQuery click() event catch-all?

DaveDev picture DaveDev · Sep 21, 2010 · Viewed 21.3k times · Source

we're showing a box on the screen that I want to hide when the user clicks anywhere on the screen, including body, anchors, divs, buttons, etc... Is there a selector that can handle this for me? Or is it a case of $('body, a, div, input').click()?

Answer

Nick Craver picture Nick Craver · Sep 21, 2010

You can do it like this:

$(document).click(function() {
  $("#boxID").hide();
});

Since the click events will, by default, bubble up to document, this is a "catch all" approach...if you don't want clicks from inside the box to close it, add a .stopPropagation() call on those click events like this:

$("#boxID").click(function(e) {
  e.stopPropagation();
});