jQuery click() event catch-all?
Asked Answered
M

2

12

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()?

Meeting answered 21/9, 2010 at 15:35 Comment(0)
B
25

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();
});
Birl answered 21/9, 2010 at 15:37 Comment(0)
L
1

You can just bind to the click event of document element. Try it at http://jsfiddle.net/ZqEbY/.

Leadbelly answered 21/9, 2010 at 15:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.