Javascript visibilty api

HTML 5 spec include nice api that allow us to know from the javascript if the page is visible to the user or not. we can also listen to event that is fired every time the visibility state change.

The java script event for change in visibility is visibilitychange so we can listen to this event, and when it is fired to check if the page is visible.
For this we have two option. One is to check document.hidden it will give us true if the page is hidden and false if the page is visible. The second option is to check document.visibilityState and it will have the value visible and if the page is visible and the  value hidden if the page is invisible.
In the example below we will only print to the console, but in your app you can use it to decide to stop video or presentation, mute sound, maybe even sending information to the server about the user interaction with the page.

//adding event listener to change in visibility state  
document.addEventListener("visibilitychange", function () {
  if (document.hidden){ //if document.hidden is true then the page is not visible, if document.hidden is false then page is visible 
  } else {
  if (document.visibilityState === "hidden"){
      console.log("page is hidden")
  if (document.visibilityState === "visible") {
     console.log("page is visible");

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s