Martti Laine
Martti Laine

Reputation: 12985

Box disappear, when clicking elsewhere on the document? (jQuery)

I'm showing a hidden box with jQuery on link-click. Now the box disappears when clicking the link again, but how to make it so it kinda "loses focus" and hides. SO, when user click somewhere on document (but not the box itself), it disappears.

Suggestions?

Martti Laine

Upvotes: 1

Views: 1070

Answers (1)

Nick Craver
Nick Craver

Reputation: 630409

A click on the box will bubble to the document, so catching a click there will always close it. To prevent this, a click inside the box will be caught/stopped, a click outside won't, causing it to bubble up and close. All the code you need to do this is:

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

$("#myBox").click(function(e) {
  e.stopPropogation();
});

...

Upvotes: 3

Related Questions