How to Toggle Fullscreen Mode with JavaScript

The JavaScript Fullscreen API allows web developers to dynamically present any DOM element across the user’s entire screen, removing browser chrome and other interface elements for an immersive experience. Toggling this view requires checking the current display state using document.fullscreenElement and conditionally calling requestFullscreen() to enter fullscreen mode or exitFullscreen() to leave it. This article explains the core methods, properties, and event listeners required to build an efficient fullscreen toggle function in JavaScript.

Core Methods and Properties

The Fullscreen API relies on three primary components to manage presentation states:

Implementing the Toggle Logic

To toggle an element’s presentation, you check whether document.fullscreenElement holds a reference to any element. If it is null, you request fullscreen for the target element; otherwise, you exit fullscreen mode.

function toggleFullscreen(element = document.documentElement) {
  if (!document.fullscreenElement) {
    element.requestFullscreen().catch((err) => {
      console.error(`Error attempting to enable fullscreen: ${err.message}`);
    });
  } else {
    document.exitFullscreen().catch((err) => {
      console.error(`Error attempting to exit fullscreen: ${err.message}`);
    });
  }
}

Passing document.documentElement expands the entire webpage, while passing a specific element (such as a <video> or <div>) will constrain the fullscreen view exclusively to that element.

Listening to State Changes

Because users can exit fullscreen presentation using native browser controls (such as the Esc key), your user interface should synchronize with state changes using the fullscreenchange event.

document.addEventListener('fullscreenchange', () => {
  if (document.fullscreenElement) {
    console.log(`Element ${document.fullscreenElement.id} entered fullscreen.`);
  } else {
    console.log('Exited fullscreen mode.');
  }
});

Styling Fullscreen Elements with CSS

When an element enters fullscreen mode, CSS provides the :fullscreen pseudo-class to adjust styling specifically for full-display presentation:

.media-container:fullscreen {
  width: 100vw;
  height: 100vh;
  background-color: #000;
  display: flex;
  align-items: center;
  justify-content: center;
}

Security and Permissions

Browsers enforce strict security rules around the Fullscreen API. Calling requestFullscreen() must be initiated by direct user interaction, such as a click or keydown event. Attempting to trigger fullscreen programmatically without user intent will reject the returned Promise and trigger a fullscreenerror event. Additionally, elements inside an <iframe> require the allow="fullscreen" attribute to use this functionality.