2 min read

Fullscreen API

The Fullscreen API provides an easy way for web content to be presented using the user's entire screen. The API lets you direct the browser to make an element and its children, if any, occupy the fullscreen, eliminating all browser user interface elements and other applications from the screen.

1. Requesting Fullscreen

To make an element go fullscreen, you call the requestFullscreen() method on that element. This method returns a Promise.

const element = document.getElementById("my-video");

function openFullscreen() {
  if (element.requestFullscreen) {
    element.requestFullscreen();
  } else if (element.webkitRequestFullscreen) { /* Safari */
    element.webkitRequestFullscreen();
  } else if (element.msRequestFullscreen) { /* IE11 */
    element.msRequestFullscreen();
  }
}

Note: While modern browsers support the standard requestFullscreen, older versions or specific browsers (like Safari on iOS) might still require vendor prefixes.

2. Exiting Fullscreen

To exit fullscreen mode, you call the exitFullscreen() method on the document object (not the element).

function closeFullscreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.webkitExitFullscreen) { /* Safari */
    document.webkitExitFullscreen();
  } else if (document.msExitFullscreen) { /* IE11 */
    document.msExitFullscreen();
  }
}

3. Checking Fullscreen State

You can check if the document is currently in fullscreen mode by looking at document.fullscreenElement. It returns the element that is currently in fullscreen mode, or null if not in fullscreen mode.

function toggleFullscreen() {
  if (!document.fullscreenElement) {
    openFullscreen();
  } else {
    closeFullscreen();
  }
}

4. Events

The API provides events to detect when the fullscreen mode changes or if an error occurs.

  • fullscreenchange: Fired when the browser enters or leaves fullscreen mode.
  • fullscreenerror: Fired when an attempt to switch to fullscreen mode fails.
document.addEventListener("fullscreenchange", (event) => {
  if (document.fullscreenElement) {
    console.log(`Element: ${document.fullscreenElement.id} entered fullscreen mode.`);
  } else {
    console.log("Leaving fullscreen mode.");
  }
});

5. CSS Styling

You can style the element specifically when it is in fullscreen mode using the :fullscreen pseudo-class.

/* Standard syntax */
:fullscreen {
  background-color: black;
  color: white;
}

/* Vendor prefixes might be needed for older support */
::backdrop {
  background-color: black; /* Styles the area behind the element */
}

programming/javascript/vanilla/javascript programming/javascript/vanilla/dom-manipulation