title: jQuery UI - Close Dialog When Clicked Outside
body: <p>I have a jQuery UI Dialog that gets displayed when specific elements are clicked.  I would like to close the dialog if a click occurs anywhere other than on those triggering elements or the dialog itself.</p>
  
  <p>Here's the code for opening the dialog:</p>
  
  <pre><code>$(document).ready(function() {
      var $field_hint = $('&lt;div&gt;&lt;/div&gt;')
          .dialog({
              autoOpen: false,
              minHeight: 50,
              resizable: false,
              width: 375
          });
  
      $('.hint').click(function() {
          var $hint = $(this);
          $field_hint.html($hint.html());
          $field_hint.dialog('option', 'position', [162, $hint.offset().top + 25]);
          $field_hint.dialog('option', 'title', $hint.siblings('label').html());
          $field_hint.dialog('open');
      });
      /*$(document).click(function() {
          $field_hint.dialog('close');
      });*/
  });
  </code></pre>
  
  <p>If I uncomment the last part, the dialog never opens. I assume it's because the same click that opens the dialog is closing it again.</p>
  
  <hr>
  
  <p><strong>Final Working Code</strong><br>
  <em>Note: This is using the <a href="http://benalman.com/projects/jquery-outside-events-plugin/" rel="noreferrer" title="jQuery outside events">jQuery outside events</a> plugin</em></p>
  
  <pre><code>$(document).ready(function() {
      // dialog element to .hint
      var $field_hint = $('&lt;div&gt;&lt;/div&gt;')
              .dialog({
                  autoOpen: false,
                  minHeight: 0,
                  resizable: false,
                  width: 376
              })
              .bind('clickoutside', function(e) {
                  $target = $(e.target);
                  if (!$target.filter('.hint').length
                          &amp;&amp; !$target.filter('.hintclickicon').length) {
                      $field_hint.dialog('close');
                  }
              });
  
      // attach dialog element to .hint elements
      $('.hint').click(function() {
          var $hint = $(this);
          $field_hint.html('&lt;div style="max-height: 300px;"&gt;' + $hint.html() + '&lt;/div&gt;');
          $field_hint.dialog('option', 'position', [$hint.offset().left - 384, $hint.offset().top + 24 - $(document).scrollTop()]);
          $field_hint.dialog('option', 'title', $hint.siblings('label').html());
          $field_hint.dialog('open');
      });
  
      // trigger .hint dialog with an anchor tag referencing the form element
      $('.hintclickicon').click(function(e) {
          e.preventDefault();
          $($(this).get(0).hash + ' .hint').trigger('click');
      });
  });
  </code></pre>