title: Detect if browser tab is active or user has switched away
body: <p>How can I detect if a user is switching to another browser tab?</p>
  
  <p>Currently, I have this: </p>
  
  <pre><code>$(window).on("blur focus", function (e) {
  
      var prevType = $(this).data("prevType");
  
      if (prevType != e.type) { //  reduce double fire issues
          switch (e.type) {
              case "blur":
                  $('.message').html('&lt;div class="alert alert-error"&gt;Oops. You navigated away from the ads &lt;a id="start" class="butt green"&gt;Resume&lt;/a&gt;&lt;/div&gt;');
  
                  var myDiv = $("#bar");
                  myDiv.clearQueue();
                  myDiv.stop();
                  clearInterval($timer);
                  $timer = null;
                  break;
              case "focus":
                  // do work
                  break;
          }
      }
  
      $(this).data("prevType", e.type);
  });
  </code></pre>
  
  <p>But that only works when the user is minimizing the active window.</p>