<body>
<div id="aaa">
<div id="bbb">
</div>
</div>
</body>
$(#?????).click(function(){
$('#bbb').hide();
})
What i must use if i want hide #bbb if user click outside box #bbb? But if i click on div #bbb then box is still visible – only outside.
A note of explanation: There are a few ways to do this, either way we need to listen for a click on a parent element, weather it be a direct parent like
#aaaor a distant parent like thebodyor thedocument. This way we can capture clicks that occur outside of#bbb.Now that we have that we need the
.hideto NOT occur if the user did click inside of#bbb. We can do this two waysStop propagation if the user clicks on
#bbb. This will make the click event not ‘bubble’ up to the parent. That way the click event never reaches the parent and so#bbbwill not hide. I personally don’t like this method because stop propagation will so ALL click events from bubbling, and you may have click events that you would like to bubble to a local parent and not a distant parent. Or you may have listeners delegated from a distant parent, which will stop working if click propagation is stopped.Check for the
#bbbelement in the parent listener. This is the method shown above. Basically this listens on a distant parent, and when a click occurs it checks to see if that click is on#bbbspecifically. If it IS NOT on#bbb.hideis fired, otherwise it returns true, so other things that may be tied into theclickevent will continue working. I prefer this method for that reason alone, but secondarily its a-little bit more readable and understandable.Finally the manner in which you check to see if the click originated at
#bbbyou have many options. Any will work, the pattern is the real meat of this thing.http://jsfiddle.net/tpBq4/ //Modded from @Raminson who’s answer is very similar.
New suggestion, leverage event bubbling without jQuery.