Sign in
Log inSign up

Add fullscreen functionality in your javascript client app.

Rajesh Tiwari's photo
Rajesh Tiwari
·Dec 24, 2019

The Fullscreen API adds methods to present a specific Element (and its descendants) in full-screen mode, and to exit full-screen mode once it is no longer needed. This makes it possible to present desired content-such as an online game-using the user's entire screen, removing all browser user interface elements and other applications from the screen until full-screen mode is shut off.

The Fullscreen API adds methods to the Document and Element interfaces to allow turning off and on full-screen mode.

Element.requestFullscreen() Asks the user agent to place the specified element (and, by extension, its descendants) into full-screen mode, removing all of the browser's UI elements as well as all other applications from the screen. Returns a Promise which is resolved once full-screen mode has been activated.

Properties

DocumentOrShadowRoot.fullscreenElement

The fullscreenElement property tells you the Element that's currently being displayed in full-screen mode on the DOM (or shadow DOM). If this is null, the document is not in full-screen mode.

document.fullscreenEnabled

The fullscreenEnabled property tells you whether or not it is possible to engage full-screen mode. This is false if full-screen mode is not available for any reason (such as the "fullscreen" feature not being allowed, or full-screen mode not being supported).

Event handlers

Document.onfullscreenchange

An event handler for the fullscreenchange event that's sent to a Document when that document is placed into full-screen mode, or when that document exits full-screen mode.

Document.onfullscreenerror

An event handler for the fullscreenerror event that gets sent to a Document when an error occurs while trying to enable or disable full-screen mode for the entire document.

Element.onfullscreenchange

An event handler which is called when the fullscreenchange event is sent to the element, indicating that the element has been placed into, or removed from, full-screen mode.

Element.onfullscreenerror

An event handler for the fullscreenerror event when sent to an element which has encountered an error while transitioning into or out of full-screen mode.

Example:-

When the page is loaded, this code is run to set up an event listener to watch for the Enter key.

document.addEventListener("keypress", function(e) {
  if (e.keyCode === 13) {
    toggleFullScreen();
  }
}, false);

This code is called by the event handler above when the user hits the Enter key.

function toggleFullScreen() {
  if (!document.fullscreenElement) {
      document.documentElement.requestFullscreen();
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen(); 
    }
  }
}

If full-screen mode is already active (fullscreenElement is not null), we call exitFullscreen() on the document to shut off full-screen mode.