title: Destroying a dialog when it loses focus
body: <p>I have a program where I have jQuery UI dialogs. I wish that those dialogs would be closed when they lose focus e.g. the user clicks anywhere outside the dialogs in question. </p>
  
  <p>On the surface this seems like a simple problem, but the <code>blur</code> event didn't work at all. After that I moved on to <code>focusin</code> and <code>focusout</code>, but stumbled upon a strange problem:</p>
  
  <p>When I have a dialog and have attached <code>focusin</code> and <code>focusout</code> to the element containing the dialog (the parent of the element I called <code>dialog</code> on). The first click after the dialog's appearing ALWAYS produces a <code>focusout</code> event regardless of where the click lands. </p>
  
  <p>So if I would like to destroy the dialog on <code>focusout</code>, the dialog gets destroyed when it shouldn't be. Here is <a href="http://jsfiddle.net/DB4E7/1/" rel="nofollow">jsFiddle</a> that demonstrates my problem.</p>
  
  <p>I know I could use some trick to ignore the first <code>focusout</code>, but I'd like to know if there is any way to get this working the right way, which is that the only event is produced when the user clicks outside the dialog for the first time.</p>
  
  <h3>UPDATE:</h3>
  
  <p>I found an agreeable answer to my question with the help of <code>underscore.js</code>:</p>
  
  <p>I broke my problem down to parts: </p>
  
  <ol>
  <li>A <code>focusout</code> happens on the first click</li>
  <li>If the click was OUTSIDE the dialog, there were no further events</li>
  <li>If the click was INSIDE the dialog, a <code>focusin</code> event followed</li>
  </ol>
  
  <p>So the undesired behavior took place when there was a sequence of <code>focusout</code>-><code>focusin</code>. I used underscore's <code>defer</code> function and a boolean modifier to tackle this problem</p>
  
  <pre><code>onFocusout: function(event) {
    console.log('focus out');
    this.hasFocus = false;
    var self = this;
    _.defer(function() {
      if (!self.hasFocus) alert('DESTROY DIALOG');
    });
  },
  
  onFocusin: function() {
    console.log('focus in');
    this.hasFocus = true;
  },
  </code></pre>
  
  <p><code>defer</code> makes the function wait until the call stack has cleared (in the bad behaving case, there is a <code>focusin</code> event waiting in the stack) and then executes it. So if <code>onFocusin</code> is fired right after <code>onFocusout</code> the <code>hasFocus</code> variable is changed to <code>true</code> and the deferred function will not destroy the dialog!</p>
  
  <p>Thank you for your answers!</p>