JavaScript Function to Exit Fullscreen Mode: A Complete Guide

Rumman Ansari   Software Engineer   2024-07-28 02:35:14   552  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

Here is a JavaScript function that can be used to exit fullscreen mode on a webpage:


function exitFullscreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen();
  } else if (document.msExitFullscreen) {
    document.msExitFullscreen();
  }
}

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", exitFullscreen);

This will exit fullscreen mode 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).

I hope this helps! Let me know if you have any questions or need further assistance.

Full Code in one place both make full screen and exit from full screen.


<!DOCTYPE html>
<html>
<body>

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

</body>
</html> 


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

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();
  }
}

function exitFullscreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen();
  } else if (document.msExitFullscreen) {
    document.msExitFullscreen();
  }
}
</script>



Stay Ahead of the Curve! Check out these trending topics and sharpen your skills.