Categories

Full Screen with JavaScript

Posted on: March 21, 2018 by Dimitar Ivanov

What is fullscreen?

A full screen is a mode where a document or element is displayed on the entire device screen. The full screen mode best fits with video element, iframe element, slideshow galleries.

The old fashioned way to activate the fullscreen mode is by pressing the F11 key on the keyboard. To deactivate the fullscreen press the F11 key again or the ESC key. However, the fullscreen mode could be controlled programmatically with the help of Javascript Fullscreen API.

Check browser support

To check if browser supports fullscreen use the fullscreenEnabled attribute, a part from Document interface.

if (document.fullscreenEnabled) {
    // supported
}

Activating fullscreen

To make a document element being displayed in fullscreen use the requestFullscreen method, a part of Element interface.

document.documentElement.requestFullscreen();
// or
document.querySelector("#video").requestFullscreen();

Cancelling fullscreen

To stop a document element from being displayed in fullscreen use the exitFullscreen method, a part from Document interface.

document.exitFullscreen();

Detecting fullscreen state change

To find out when full screen is being requested or cancelled make your app listen for changes in fullscreen state.

document.addEventListener("fullscreenchange", function (event) {
    if (document.fullscreenElement) {
        // fullscreen is activated
    } else {
        // fullscreen is cancelled
    }
});

Error handling

To improve the user experience make your app listen for errors.

document.addEventListener("fullscreenerror", function (event) {
    // an error occurred
});

Styling fullscreen

To slylish a fullscreen element and it's children use the :fullscreen pseudo-class.

:fullscreen {
    background-color: red;
}

To see the above code in action go to our Fullscreen demo page.

Browser Compatibility

Chrome 15, Firefox 10, IE 11, Opera 12.1, Safari 5.1

See also
Share this post

If you have any questions about the Fullscreen API, leave a comment below. And do not be shy to share this article. Thanks so much for reading.


0 Comments

Leave a comment

Captcha