Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

visibilitychange — document visibility changes

The visibilitychange event reports a change in document visibility. Read the current state from document.visibilityState.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

document.addEventListener("visibilitychange", handler);

visibilitychange is an event on document, fired after its visibility state changes. document.visibilityState returns "visible" or "hidden"; document.hidden is the Boolean equivalent of the latter value.

The browser determines visibility, for example when switching tabs or minimizing a window. The event bubbles. Use it to reduce unnecessary work on a hidden page.

The example uses dispatchEvent to dispatch one synthetic visibilitychange event without switching tabs or changing document visibility. The listener runs only once because it is registered with once: true. It labels the event synthetic in the console and checks whether document.visibilityState is "visible" or "hidden". It logs the Boolean result (true), not the state itself.

Examples

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Testing a visibilitychange listener</title>
</head>
<body>
<script>
  document.addEventListener('visibilitychange', (event) => {
    // In normal use, read the current state when the browser fires this event.
    const state = document.visibilityState;
    const valid = state === 'visible' || state === 'hidden';
    console.log(`${event.type} (${event.isTrusted ? 'browser' : 'synthetic'}): valid visibilityState = ${valid}`);
  }, { once: true });

  // Exercise the listener without switching tabs or changing visibility.
  document.dispatchEvent(new Event('visibilitychange'));
</script>
</body>
</html>

Result

visibilitychange (synthetic): valid visibilityState = true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources