Making video fullscreen automatically when the device orientation is landscape with javascript

Viewed 2135

I have a video that if you press a button it becomes fullscreen. I need help making the video fullscreen automatically when the device is in landscape orientation. I have tried many ways but none have worked.

Here is my code:

var elem = document.getElementById("video");

function becomeFullscreen() {
  if (elem.requestFullscreen) {
    elem.requestFullscreen();
  } else if (elem.mozRequestFullScreen) {
    /* Firefox */
    elem.mozRequestFullScreen();
  } else if (elem.webkitRequestFullscreen) {
    /* Chrome, Safari and Opera */
    elem.webkitRequestFullscreen();
  } else if (elem.msRequestFullscreen) {
    /* IE/Edge */
    elem.msRequestFullscreen();
  }
}
<video id="video" width="600" height="800">
            <source src="videoplaceholder.mp4" />
        </video>

<button id="button" onclick="becomeFullscreen()">Fullscreen</button>

2 Answers

Add below code in your Javascript

window.addEventListener("orientationchange", function(event) {
  var orientation = (screen.orientation || {}).type || screen.mozOrientation || screen.msOrientation;

if ( ["landscape-primary","landscape-secondary"].indexOf(orientation)!=-1) {
  becomeFullscreen();
}

else if (orientation === undefined) {
  console.log("The orientation API isn't supported in this browser :("); 
}
});
Related