title: how to close jQuery tooltip
body: <p>I've been trying to make very simple javascript tooltip with jQuery but I've hit a brick wall. The idea is to have little inline element (<code>span</code>) inside a <code>div</code>. The <code>span</code> element will contain a tooltip <code>div</code> with a little html (image and link). Tooltip should be opened when clicked on the <code>span</code> element and closed when clicked outside of it or outside of the tooltip.</p>
  
  <p>So far, opening the tooltip is not a problem but closing is.</p>
  
  <pre><code>&lt;!DOCTYPE HTML&gt;
  &lt;html&gt;
  &lt;head&gt;
      &lt;title&gt;&lt;/title&gt;
  
      &lt;style&gt;
          #colors &gt; div {
              background-color: red;
              height: 50px;
              width: 50px;
              margin: 5px;
          }
  
          #colors &gt; div &gt; span {
              min-height: 10px !important;
              min-width: 10px !important;
              border: 3px solid black;
              position: relative;
          }
  
          .tooltip {
              border: 2px solid blue;
              display: none;
          }
      &lt;/style&gt;
  
      &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"&gt;&lt;/script&gt;
      &lt;script&gt;
          $(function () {
              // generate boxes and tooltips
              for (var i = 0; i &lt; 9; i++) {
                  $('#colors').append('&lt;div id="' + i + '"&gt;&lt;span&gt;&lt;div class="tooltip"&gt;&lt;a href="#"&gt;add to favorites&lt;/a&gt;&lt;/div&gt;&lt;/span&gt;&lt;/div&gt;');
              }
  
              $('#colors').delegate('span', 'click', function (event) {
                  $(this).children('.tooltip').css({position:'absolute', top:'5px', left:'5px'}).fadeIn();
                  // bottom one won't work
                  //event.stopPropagation();
              });
  
              $(document).delegate('body', 'click', function (event) {
                  var that = this
                  $.each($('.tooltip'), function (index, element) {
                      // it's always visible ...
                      //if ($(element).is(':visible')) {
  
                      // doesn't work either
                      if ($(element).is(':visible') &amp;&amp; $(element).has(event.target).length === 0) {
                          var s = event.target;
  
                          console.log([($(s) == event.target), event.target, index, element, $(element).has(event.target).length, that]);
                      }
                  });
              });
          })
      &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;div id="colors"&gt;&lt;/div&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>I can't seem to find a way to close the tooltip if click is outside of the <code>span</code> and tooltip. </p>