tags:

views:

52

answers:

2

Hello,

Here's my problem:

I have a div element that when it's clicked, another div shows up. Now I have no idea how to make that wherever I click on the page, this div gets removed. I mean, I know how to remove it, but which kind of events should I have in consideration to do such thing!? I can't make it with focus/blur can I. I mean I tried and it doesn't work so I guess not. Probably it's very simple but I guess I 'm to new to this ...

Cheeers

+5  A: 

When you add it to the DOM, you could also create a one-time click event handler and attach it to the document. Something like

// <div> has just been added to the DOM
$(document).one("click", function() { $('#theDiv').remove(); });

Here's a Working Demo. add /edit to the URL to see the code

Russ Cam
thanks, but I just tried out that solution, and the problem is that one click event gets triggered at the same time I click on the first div.
CharlesM
it's because the event bubbles up the DOM after the `<div>` element is clicked. You need to `return false` or use `event.preventDefault();`
Russ Cam
Thanks! It works!
CharlesM
+1  A: 

I saw a different question today, but it incorporated a similar mechanism.

Basically you want to attach a click handler to the document but only fire it if the click does not originate within certain objects:

With this HTML:

<div id="menu">Click Me</div>
<div id="other-popup"> Wow, I have been shown!</div>

Use this (or something similar):

$(document).click(function(e){
   var $target = $(e.target);
   // For all clicks except those in the menu or the popup, hide the popup
   if(!$target.closest("#menu").length && !$target.closest("#other-popup").length ){
      $("#other-popup").hide();
   }
});

closest() looks in the current node and the ancestor nodes for a match.

Doug Neiner