JavaScript function that can be used to make a webpage fullscreen

Rumman Ansari   Software Engineer   2023-03-26   254 Share
☰ Table of Contents

Table of Content:


Here is a JavaScript function that can be used to make a webpage fullscreen:


function makeFullscreen() {
  var element = document.documentElement;
  if (element.requestFullscreen) {
    element.requestFullscreen();
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullscreen();
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen();
  }
}

To use this function, you can call it from an event handler, such as a button click or a key press. For example:


document.getElementById("myButton").addEventListener("click", makeFullscreen);

This will make the webpage fullscreen when the button with the ID "myButton" is clicked.

Note that the fullscreen mode is only supported by modern web browsers, and it requires the user's permission. The user can exit fullscreen mode by pressing the "Esc" key or by clicking the "Exit fullscreen" button (if available).


Full Code in one place. You can copy it and try it.


<!DOCTYPE html>
<html>
<body>

<h2>Java Script Full Screen</h2> 
<button type="button" id = "myButton"> Full Screen </button>  

</body>
</html> 


<script>
document.getElementById("myButton").addEventListener("click", makeFullscreen);

function makeFullscreen() {
  var element = document.documentElement;
  if (element.requestFullscreen) {
    element.requestFullscreen();
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullscreen();
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen();
  }
}
</script>