Click on another side of the hide an item

0

I'm trying that when you click on another place that was the button, hide the div, but I do not get it, I have no idea how to do.

$(function(){
  
  $(document).on('click','#foo',function(){
    let div = $('#bar');
    if( div.css('display') === 'none' ){
      div.show();
    }
    
    else{
      div.hide();
    }
  });

})
#foo{
  min-width: 35%;
}

#bar{
  max-width: 35%;
  min-height: 100px;
  background-color: aliceblue;
  border: 1px solid blue;
  border-radius: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="foo">Toggle</button><br><br>
<div id="bar"></div>

It occurred to me with

  $(document).on('click','html',function(e){
    if(e.eventTarget !== 'foo'){
      $('#bar').hide();
    }
  });

But first the page is locked and the second is not correct code, just simulates what I intend to achieve.

    
asked by Alberto Siurob 04.05.2018 в 06:02
source

1 answer

0

The way you came up with is the correct one, only instead of delegating the html tag you should delegate it to body

$(document).on('click','body',function(e){
    if(e.eventTarget !== 'foo'){
      $('#bar').hide();
    }
});
    
answered by 04.05.2018 в 06:16