3

I've a HTML div and I want to hide it whenever the user clicks on the page anywhere outside the div. Which clicking on which element should I trigger the onclick event??

3 Answers 3

6
$('#mydiv').click(function(e) { e.stopImmediatePropagation(); });
$(document.body).one("click", function() {
    $('#mydiv').hide();
});

Since mydiv is also a child of the body element, you don't want that when clicking on that element, the element would dissappear.
So when people click on the mydiv, you want it to stop bubbling up to the body element, that is why first you register a click event on your mydiv, and tell it to stop bubbling.

1
  • Uh, .one() takes in an eventType as an argument. Here, what event are you binding once? Nov 29, 2010 at 7:56
1

Assuming you're using the latest jQuery, v1.4.4:

$(<the div you want hidden>).click(false); //stop click event from bubbling up to the document
$(document).one('click', function(){
  $(<the div you want hidden>).hide(); //which will hide the div
});

In other words, this code says 'hide the div if you click on this page, unless you click on the div'.

Re: Toggle button

Then you'll have something like:

$('button').click(function(){
  $('div').toggle();
});
$('div').click(false);
$(document).click(function(){
  $('div').hide();
  //reset the toggle state, e.g.
  $('button').removeClass('selected');
});
3
  • I've a toggle button. Toggling on which will show and hide the div. Apart from that, I want to hide the div on clicking anywhere outside the div. I'm trying to create something like the twitter 'Sign In' button at twitter.com
    – ptamzz
    Nov 29, 2010 at 7:57
  • Can you help me reset the toggle state. Suppose after I clicked on one element, when I click on another element, it should reset the toggle state to the initial one. Thanks :)
    – ptamzz
    Nov 29, 2010 at 8:30
  • I'm not sure what you mean, but I marked the appropriate place to reset the toggle state. Nov 29, 2010 at 8:37
0

The BODY element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.