carapaece
carapaece

Reputation: 351

JavaScript: How to toggle HTML5 video fullscreen / non-fullscreen?

Given is an HTML5 video element. A button should change this video element into fullscreen, or end the fullscreen.

I have already written a JavaScript function. This works fine in Firefox. Unfortunately, the function does not work in Google Chrome.

function toggleFullScreen() {
    var player = document.querySelector('#playerContainer');
    if (!document.mozFullScreen && !document.webkitFullScreen) {
        if (player.mozRequestFullScreen) {
            player.mozRequestFullScreen();
        } 
        else {
            player.webkitRequestFullScreen();
        }
    } else {
        if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else {
            document.webkitCancelFullScreen();
        }
    }
}

While everything works fine in Firefox, in Chrome, the window is positioned only in the middle of the full-screen window. Also, Chrome can not quit the fullscreen.

I used Firefox Quantum 61.0.1 and Google Chrome 68.0.

Upvotes: 0

Views: 2283

Answers (2)

carapaece
carapaece

Reputation: 351

I solved my problem... it failed because I used the wrong function in the first if-statement:

Wrong:

if (!document.mozFullScreen && !document.webkitFullScreen) { ... }

Correct:

if (!document.mozFullScreen && !document.webkitIsFullScreen) { ... }

Upvotes: 0

Bin Liang
Bin Liang

Reputation: 11

I see a note in devdocs, maybe useful for you:

It's worth noting a key difference here between the Gecko and WebKit implementations at this time: Gecko automatically adds CSS rules to the element to stretch it to fill the screen: width: 100%; height: 100%

WebKit doesn't do this. Instead, it centers the fullscreen element at the same size in a screen that's otherwise black. To get the same fullscreen behavior in WebKit, you need to add your own "width: 100%; height: 100%;" CSS rules to the element yourself:

#myvideo:-webkit-full-screen {
    width: 100%;
    height: 100%;
}

Upvotes: 1

Related Questions