How to Check If the Browser Has the Focus in JavaScript

How to Check If the Browser Has the Focus in JavaScript thumbnail
It's a good idea to check to see if the browser is in focus before running persistent functions.

More and more Web pages are incorporating JavaScript functions that run in loops at regular intervals, either to ping a URL for updates or to provide greater user interactivity with the page. Unfortunately, JavaScript consumes the resources of the client's machine, including central processing unit usage, memory and bandwidth.



With that in mind, it's considered good practice for programmers to not tax those resources when the user doesn't have need for them. One way to do that is to check if the browser (or a specific tab within the browser) has focus, and enable/disable functions accordingly.

Instructions

    • 1

      Create two functions, one for when the browser is in focus, and one for when its focus is blurred:

      var onFocus = function() {

      // insert code to run when the window has gained focus.

      };

      var onBlur = function() {

      // insert code to run when the window has lost focus.

      };

    • 2

      Incorporate feature detection. This is primarily for Internet Explorer, but it's best to use feature detection rather than browser detection because it's more reliable to directly test for the feature you want to manipulate. Internet Explorer uses the property document.onfocusin and document.onfocusout rather than window.onfocus and window.onbur, so you will need to check to see if those document properties are defined:

      if (document.onfocusin !== undefined) {

      var onfocusin = true;

      } else {

      var onfocusin = false;

      }

    • 3

      Complete the code by binding the appropriate focus/blur events to the functions created in Step 1:

      if (onfocusin === true) {

      document.onfocusin = onFocus;

      document.onfocusout = onBlur;

      } else {

      window.onfocus = onFocus;

      window.onblur = onBlur;

      }

Tips & Warnings

  • Remember to check your code in every browser that your site supports before taking it live. The code in this article has been tested in Firefox 3.6.6, IE 7, IE 8, Chrome 6.0, Safari 5.0 and Opera 10.53.

Related Searches:

References

  • Photo Credit code image by charles taylor from Fotolia.com

Comments

You May Also Like

Related Ads

Featured