Javascript DOM fullscreenchange Event

Introduction

Display some text when the page is viewed in full screen mode:

Click on the button to open this page in full screen mode.

Press the "Esc" key to exit full screen.

View in separate window

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#myP {//ww w  .  j  a  va 2  s  . co m
  background-color: yellow;
  padding: 20px;
  font-size: 30px;
}
</style>
</head>
<body>
<button onclick="openFullscreen();">Go Full screen Mode</button>
<button onclick="closeFullscreen();">Close Full screen</button>
<p id="myP"></p>

<script>
/* Get the element you want displayed in fullscreen */
var elem = document.documentElement;

/* Function to open fullscreen mode */
function openFullscreen() {
  if (elem.requestFullscreen) {
    elem.requestFullscreen();
  } else if (elem.mozRequestFullScreen) { /* Firefox */
    elem.mozRequestFullScreen();
  } else if (elem.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
    elem.webkitRequestFullscreen();
  } else if (elem.msRequestFullscreen) { /* IE/Edge */
    elem = window.top.document.body; //To break out of frame in IE
    elem.msRequestFullscreen();
  }
}

/* Function to close fullscreen mode */
function closeFullscreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen();
  } else if (document.msExitFullscreen) {
    window.top.document.msExitFullscreen();
  }
}

// Events
var output = document.getElementById("myP");
document.addEventListener("fullscreenchange", function() {
  output.innerHTML = "fullscreenchange event fired!";
});
document.addEventListener("mozfullscreenchange", function() {
  output.innerHTML = "mozfullscreenchange event fired!";
});
document.addEventListener("webkitfullscreenchange", function() {
  output.innerHTML = "webkitfullscreenchange event fired!";
});
document.addEventListener("msfullscreenchange", function() {
  output.innerHTML = "msfullscreenchange event fired!";
});
</script>
</body>
</html>

The fullscreenchange event occurs when an element is viewed in full screen mode.

This event requires specific prefixes to work in different browsers.

Use the element.requestFullscreen() method to view an element in full screen mode.

Use the element.exitFullscreen() method to cancel full screen mode.




PreviousNext

Related