martin
martin

Reputation: 413

How to detect fullscreen using document.msFullscreenElement !== null (with javascript)

Using 'document.msFullscreenElement !== null', as per the answer given in here:

I am trying to detect if a page is in Fullscreen mode in IE11:

<!DOCTYPE html>
<head>
<title>Detect Fullscreen</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
var inFullscreen = document.msFullscreenElement !== null; 
alert("inFullscreen is " + inFullscreen);
</script>
</head>
<body>
<p>Detect Fullscreen in IE11</p>
</body>
</html>

However, the outcome of the alert is false whether or not the browser is in fullscreen. Presumably I misunderstand how this meant to be applied?

Upvotes: 1

Views: 1572

Answers (1)

etr
etr

Reputation: 1262

The MSFullscreenChange event is fired after an element enters or exits full-screen mode, so you can get the current state. In the example, we check the msFullscreenElement to see if any elements are in full screen. If an element is in full-screen mode, the element is returned, otherwise msFullscreenElement returns null.

if (document.requestFullscreen) {
  document.addEventListener("fullscreenchange", function () {
    if (document.fullscreenElement != null) {
      console.info("Went full screen");
    } else {
      console.info("Exited full screen");
    }
  });
}
else if (document.msRequestFullscreen) {
  document.addEventListener("MSFullscreenChange", function () {
    if (document.msFullscreenElement != null) {
      console.info("Went full screen");
    } else {
      console.info("Exited full screen");
    }
  });
}

Upvotes: 2

Related Questions