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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With