Mick Asgorther Mick Asgorther - 11 months ago 84
HTML Question

click outside DIV

<div id="aaa">
<div id="bbb">





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.

Answer Source
       if( e.target.id == 'bbb' )
          { return true; }
          { $('#bbb').hide(); }


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 #aaa or a distant parent like the body or the document. This way we can capture clicks that occur outside of #bbb.

Now that we have that we need the .hide to NOT occur if the user did click inside of #bbb. We can do this two ways

  1. Stop 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 #bbb will 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.

  2. Check for the #bbb element 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 #bbb specifically. If it IS NOT on #bbb .hide is fired, otherwise it returns true, so other things that may be tied into the click event 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 #bbb you 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.

var isOutSide = true
    bbb       = documment.getElementById('bbb');
document.body.addEventListener('click', function(){
       bbb.style.display = 'none';
   isOutSide = true;

bbb.addEventListener('click', function(){
   isOutSide = false;