0

I would like to run a function whenever a browser tab is active/selected.

How do I do it using JavaScript/jQuery?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Eralph
  • 944
  • 1
  • 9
  • 23
  • Check this thread: http://stackoverflow.com/questions/10338704/javascript-to-detect-if-user-changes-tab – Anonymoose Sep 19 '12 at 07:13
  • @Hazaart I have created this code but it keeps popping out 'focus' & 'blur' couple times whenever the page loads. I don't know whats wrong. $(window).focus(function(){ alert('focus'); }); $(window).blur(function(){ alert('blur'); }); – Eralph Sep 19 '12 at 07:20

1 Answers1

0

Perhaps you can use the Page Visibility API ? The specification is at http://www.w3.org/TR/2011/WD-page-visibility-20110602/

"This specification defines a means for site developers to programmatically determine the current visibility state of the page in order to develop power and CPU efficient web applications."

There is also a handy wrapper library for it - Visibility.js at https://github.com/ai/visibility.js

Visibility.onVisible(function () {
    // do something 
});
sphair
  • 1,674
  • 15
  • 29
  • thanks. I have used this https://developer.mozilla.org/en-US/docs/DOM/Using_the_Page_Visibility_API – Eralph Sep 19 '12 at 08:53