Is there any way to detect that window is currently active in IE8?

I’ve written a jQuery plugin that does this: http://mths.be/visibility It gives you a very simple API that allows you to execute callbacks when the page’s visibility state changes.

It does so by using the the Page Visibility API where it’s supported, and falling back to good old focus and blur in older browsers.

Demo: http://mathiasbynens.be/demo/jquery-visibility

This plugin simply provides two custom events for you to use: show and hide. When the page visibility state changes, the appropriate event will be triggered.

You can use them separately:

$(document).on('show', function() {
  // the page gained visibility
});

…and…

$(document).on('hide', function() {
  // the page was hidden
});

Since most of the time you’ll need both events, your best option is to use an events map. This way, you can bind both event handlers in one go:

$(document).on({
  'show': function() {
    console.log('The page gained visibility; the `show` event was triggered.');
  },
  'hide': function() {
    console.log('The page lost visibility; the `hide` event was triggered.');
  }
});

The plugin will detect if the Page Visibility API is natively supported in the browser or not, and expose this information as a boolean (true/false) in $.support.pageVisibility:

if ($.support.pageVisibility) {
  // Page Visibility is natively supported in this browser
}

Leave a Comment