Rectangle 27 0

javascript How do I hide a div if the user clicks outside of the div?


$("#edit-button").click( function(e) {
    $("#edit").toggle();
    e.stopPropagation();
});

$('#edit').click(function(e) {
    e.stopPropagation();
});

$("body").click( function(e) {
    $("#edit").hide();
});

Added an example. You'll need to fix the ID of 'edit-button' though. Untested but should work ;)

Ah ok, in the css I changed it from visibility: hidden to display: none and now the code works. Also had to change #body -> body and show() -> toggle(). Thanks for the help.

And then if you attach an event handler to the BODY element listening for clicks, you can use that event handler to hide the DIV; knowing that a click on the DIV itself won't bubble the event up to the BODY handler.

Awesome. Thanks for editing the post with corrections.

I tried this, however the div won't even appear now. I changed the var names as needed and there are no extenuating factors in the rest of the code. I'm not particularly strong with jQuery, so perhaps I'm missing something important/obvious?

In this way any click on another element, unless the handler also calls stopPropagation(), will get caught by your handler. So if there are other cases where you don't want the div to hide you can stop it happening by calling stopPropagation() as required.

You could call 'e.stopPropagation()' on the event from within your click event handler when a user clicks within your div - this will stop the event from 'bubbling' up the DOM.

Note