Fullscreen API – Web APIs | MDN

In this example, a video is presented in a web page. Pressing the Enter key lets the user toggle between windowed and fullscreen presentation of the video.

View Live Example

Watching for the Enter key

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

document

.

addEventListener

(

"keydown"

,

(

e

)

=>

{

if

(

e

.

key

===

"Enter"

)

{

toggleFullScreen

(

)

;

}

}

,

false

)

;

Toggling fullscreen mode

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

(

)

;

}

}

This starts by looking at the value of the document‘s fullscreenElement attribute. In a real-world deployment, at this time, you’ll want to check for prefixed versions of this (mozFullScreenElement, msFullscreenElement, or webkitFullscreenElement, for example). If the value is null, the document is currently in windowed mode, so we need to switch to fullscreen mode; otherwise, it’s the element that’s currently in fullscreen mode. Switching to fullscreen mode is done by calling Element.requestFullscreen() on the <video> element.

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