Put element into fullscreen in JS

Hi there!

Today I studied How can I put an element into fullscreen mode and I want to share with you How do it ☺️

Primarily, you should know that It works only in events, so you should use request into fullscreen mode in the event function.

So that put container into fullscreen mode use it

const d = document.querySelector("#d")

d.requestFullscreen(options)
    .then(() => {})
    .catch((error) => {})

You see that it is not guaranteed that the element will be put into fullscreen mode.

So, element.requestFullscreen() returned Promise of undefined.

In options you can change navigationUI param on "hide" | "show" or "auto" (default value).

First, I create a function for get fullscreen method, because fullscreen in some browsers works with prefixes only.

function goIntoFullscreen(element) {
    if (element.requestFullscreen) {
        return element.requestFullscreen()
    } else if (element.mozRequestFullScreen) {
        return element.mozRequestFullScreen()
    } else if (element.webkitRequestFullscreen) {
        return element.webkitRequestFullscreen()
    } else if (element.msRequestFullscreen) {
        return element.msRequestFullscreen();
    }
}

Next, You should exit out of fullscreen mode.

For exit out of fullscreen mode used by document.exitFullscreen. I created a function for it with some browser prefixes too.

function outOfFullscreen() {
    if(document.exitFullscreen) {
        document.exitFullscreen()
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen()
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen()
    } else if (document.msExitFullscreen) {
        document.msExitFullscreen()
    }
}

After put into fullscreen will be available document.fullscreenElement. You can check it for the button event of something else. I wrote a simple check function for it

function isFullScreenMode() {
    return document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement || null;
}

Funnily I created an example so that you can try live demo.

You can style your fullscreen into fullscreen mode and elements in use by :fullscreen and ::backdrop.

Finally, you can be listening fullscreen with fullscreenchange and fullscreenerror events.

23