Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

visibilitychange Event

visibilitychange Event

Event Object Reference Event Object

Example

Execute a piece of JavaScript code when the content of its tab becomes visible or hidden:

document

.

addEventListener

(

'

visibilitychange

'

,

function

(

)

{

if

(

document

.

visibilityState

===

'

visible

'

)

{

//

The action to perform when the page becomes visible

}

else

if

(

document

.

visibilityState

===

'

hidden

'

)

{

//

The action to perform when the page becomes invisible

}

}

)

;

Try it »


Definition and Usage

The visibilitychange event is an event fired on the Document object in the browser, used to detect whether the visibility state of the current page has changed.

When the user switches to another tab, minimizes the browser window, or hides the browser window behind other windows, the visibility of the page changes, and the visibilitychange event is triggered.

Syntax

document.addEventListener('visibilitychange', function() {

  if (document.visibilityState === 'visible') {

    // Operations executed when the page becomes visible

  } else if (document.visibilityState === 'hidden') {

    // Operations executed when the page becomes invisible

  }

});


Browser support

Events
ondrop 62 18 56 14.1 49

**Note:**visibilitychange The behavior of the event may vary across different browsers, so you need to pay attention to browser compatibility when using it. In addition, the power-saving mode of some mobile devices or computers may also affect the visibility state of the page, thereby triggering this event.


Event Object Reference Event Object