Ironank Ironank - 9 days ago 5
Javascript Question

Show div and then hide when clicking outside

I have this code:

$(function() {
$('#toggle4').click(function() {
$('.toggle4').slideToggle('fast');
return false;
});
});


Which works great and shows the '.toggle4' div but I want to hide it again when clicking outside/away from it.

So I added this:

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


Which works but it hides the div even when I click inside of the '.toggle4' div (it's an input box for a search form).

Any ideas? Thanks.

Answer

That's because when you click inside of .toggle4 that click event bubbles up the DOM and triggers the event you bound to the document. You should be able to fix that with something like:

$('.toggle4').click(function(e){
    e.stopPropagation()
})