Enable the browser fullscreen in Javascript

0
839
views

To enable the browser fullscreen in Javascript

Javascript offers requestFullscreen() method, you can call this method with respect to any element that should be displayed on fullscreen mode.

The list given below of methods, properties, and event helps us to achieve the fullscreen functionality.

  1. requestFullscreen() – This method call triggers the element to the fullscreen mode.
  2. exitFullscreen() – This method call triggers the element to exit from the fullscreen mode.
  3. document.fullscreenElement – We use this property to check whether the element is already in fullscreen mode or not.
  4. document.fullScreenEnabled – We use this property to check whether the current page has permission to show elements in fullscreen mode
  5. fullscreenchange – This event will be used to observe fullscreen to enter and exit.

Enter fullscreen mode

function enableFullScreenMode(element) {
  if(element.requestFullscreen) {
    element.requestFullscreen();
  }else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen();     // Firefox
  }else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullscreen();  // Safari
  }else if(element.msRequestFullscreen) {
    element.msRequestFullscreen();      // IE/Edge
  }
};

Exit fullscreen mode

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

Let’s take an example to achieve fullscreen mode enter functionality.

Hereafter clicking on the button target element enters the fullscreen

<div id="target-elem" #elem></div>
<button id="fullscreen-btn" (click)=enableFullScreenMode(elem)>Enter full screen</button>

Once the function called implementation logic looks something like this

function enableFullScreenMode(element) {
  if(element.requestFullscreen) {
    element.requestFullscreen();
  }else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen();     // Firefox
  }else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullscreen();  // Safari
  }else if(element.msRequestFullscreen) {
    element.msRequestFullscreen();      // IE/Edge
  }
};

document.addEventListener('fullscreenchange', (event) => {
  if (document.fullscreenElement) {
    console.log('Entered fullscreen:', document.fullscreenElement);
  } else {
    console.log('Exited fullscreen.');
  }
});

Happy coding…