Marcos Schmell
Marcos Schmell

Reputation: 47

How to detect when a video has been taken out of fullscreen mode with javascript / jquery

I have a video that was uploaded to my html page and with the help of javascript I can put the video in full screen by clicking on a button. When that happens I can detect it without problem.

The following code allows me to put the video in full screen when I click on a button:

// Here the video in html

  <video controls id="myvideo">
      <source src="/videoPlays.mp4" type="video/mp4"></source>
  </video> 

// here javascript/jquery code to active fullscreen mode and play video

$("#BtnPlayVideo").click(VideoPlay);

function VideoPlay() {
  var elem = document.getElementById("myvideo");
  if (elem.requestFullscreen) {
    elem.requestFullscreen();
    $('#myvideo')[0].play();
  } else if (elem.mozRequestFullScreen) {
    elem.mozRequestFullScreen();
    $('#myvideo')[0].play();
  } else if (elem.webkitRequestFullscreen) {
    elem.webkitRequestFullscreen();
    $('#myvideo')[0].play();
  } else if (elem.msRequestFullscreen) {
    elem.msRequestFullscreen();
    $('#myvideo')[0].play();
  }
}

What I want to do is to detect when the user presses the button to leave the full screen mode and stop the video at that moment. Any ideas or help that you can give me to achieve this?

Upvotes: 0

Views: 2121

Answers (1)

n4m31ess_c0d3r
n4m31ess_c0d3r

Reputation: 3148

I you are using the requestFullscreen to toggle into full screen mode, then you can also listen to the fullscreenchange method to detect any change in full screen mode and use the Boolean property fullscreen to check whether the full screen mode is currently on or off.

Here's a little fiddle to show that:

https://jsfiddle.net/4z8w720a/1/

document.addEventListener("fullscreenchange", function() {
  if (document.fullscreen) {
    console.log('Entering Full Screen Toggle');
  } else {
    console.log('Exiting Full Screen Toggle');
  }
});

P.S.: These were a part of experimental APIs, so please do check their browser compatibility and future support.

Upvotes: 2

Related Questions