JS Tip of the Day: Entering Fullscreen

Entering Fullscreen
Level: Beginner

In browsers, you can programmatically enter fullscreen mode using the requestFullscreen() method. If you call this from the document object, it will put the entire page in fullscreen, but you can also call it from individual elements to only have those elements go in fullscreen.

<div id="box">I'm a box</div>
<button id="full-doc">Full Screen Document</button>
<button id="full-box">Full Screen Box</button>

<script>
document.getElementById('full-doc').addEventListener(click, event => {
    document.requestFullscreen();
    // everything full screen
});
document.getElementById('full-box').addEventListener(click, event => {
    document.getElementById('box').requestFullscreen();
    // only box full screen
});
</script>

Entering fullscreen requires permission from the user. You can use the promise returned from requestFullscreen() to know if and when the user allows it and fullscreen is finally entered.

document.requestFullscreen()
    .then(() => {
        console.log('Entered fullscreen!');
    })
    .catch(() => {
        console.log('The user likes things little.');
    });

You can also only enter fullscreen from a user-initiated action. This prevents you from doing something like immediately opening fullscreen when the page loads. The user will need to click on something like a button or press a key on their keyboard for the full screen request to be allowed.

Users can exit fullscreen using the ESC key, or you can call exitFullscreen(). This is always called from document, even if requestFullscreen() was called from an element.

document.exitFullscreen(); // exit document or element fullscreen

The fullscreen API has other features as well, including events for detecting when full screen is entered or exited. See the link below for more.

More info: