Skip to content

How to Toggle Fullscreen Mode in JavaScript

You can toggle fullscreen mode in JavaScript using the requestFullscreen() and exitFullscreen() methods. The requestFullscreen() method is used to request full screen mode for an element, and the exitFullscreen() method is used to exit full screen mode.

Here’s how you can toggle fullscreen mode in JavaScript:

const toggleFullscreen = () => {
  if (document.fullscreenElement) {
    document.exitFullscreen();
  } else {
    document.documentElement.requestFullscreen();
  }
};

// Toggle fullscreen mode on button click
const el = document.getElementById('toggleFullscreenBtn');
el.addEventListener('click', toggleFullscreen);

In the example above, we define a toggleFullscreen() function that checks if the document.fullscreenElement property is truthy. If it is, we call the document.exitFullscreen() method to exit full screen mode. If it is falsy, we call the document.documentElement.requestFullscreen() method to request full screen mode.