Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there any way to detect that the window is currently active (is being shown on active tab/window) in IE8?

I know there are events like onfocusin/onfocus - but this is not a perfect solution, since the window must also receive focus for the event to be fired - so this does not work when the user just switches the tabs without touching the window itself.

I believe there has to be some simple, elegant solution for such ordinary use-case.

like image 314
Martin Bencik Avatar asked Mar 09 '12 10:03

Martin Bencik


1 Answers

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
}
like image 137
Mathias Bynens Avatar answered Oct 29 '22 04:10

Mathias Bynens