requestFullscreen Targets One Element At A Time

Request fullscreen on one element with requestFullscreen, track it with document.fullscreenElement, and listen to fullscreenchange for Esc exits.

JavascriptData Integrity

Code

javascriptsnippet
26 lines
// Fullscreen is element-scoped: request it on the element, observe
// document.fullscreenElement, and exit with document.exitFullscreen()
const stage = document.querySelector('#stage');
const button = document.querySelector('#fullscreen');

button.addEventListener('click', async () => {
  if (document.fullscreenElement) {
    await document.exitFullscreen();
    return;
  }

  // requestFullscreen resolves once the element really fills the screen
  try {
    await stage.requestFullscreen();
  } catch (error) {
    console.log('fullscreen denied:', error.name);
    return;
  }

  console.log('fullscreen:', document.fullscreenElement === stage);
});

// fullscreenchange fires for every enter and exit, Esc included
document.addEventListener('fullscreenchange', () => {
  console.log('fullscreenchange:', Boolean(document.fullscreenElement));
});

How the snippet works

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Top-level bindings stage, button hold the demo state — nothing sits inside a function scope.

Caveats

  • The snippet leans on document — browser-only surfaces a bare Node process cannot provide.

Using it

The prefixes fullscreen denied:, fullscreen:, fullscreenchange: mark the run’s output; reading one tells you which statement ran.

Key statements

document.addEventListener('fullscreenchange', () => {
  console.log('fullscreenchange:', Boolean(document.fullscreenElement));
});
await document.exitFullscreen();
await stage.requestFullscreen();

Interactive Tools for This Topic

FAQ

Does requestFullscreen Targets One Element At A Time run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.