How to exit fullscreen onclick using Javascript?

Solutions provided here are incredibly long. You can use these few lines to show or cancel fullscreen.

Show full screen:

  /* You can use any HTML element through JS selector functions
   * eg. document.querySelector(".example");
  */
const element = document; 
const requestFullScreen = element.requestFullscreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullScreen;
requestFullScreen.call(element);

Cancel full screen:

// As correctly mentioned in the accepted answer, exitFullscreen only works on document
const cancellFullScreen = document.exitFullscreen || document.mozCancelFullScreen || document.webkitExitFullscreen || document.msExitFullscreen;
cancellFullScreen.call(document);

Chrome will display an error: Uncaught (in promise) TypeError: Document not active if exitFullscreen is called while not in fullscreen mode.


Figured it out.

Apparently, to enter full screen, you need to use the Element, however to exit fullscreen, you use document.

Here is the complete javascript function to toggle fullscreen that works !!!

function fullscreen() {
    var isInFullScreen = (document.fullscreenElement && document.fullscreenElement !== null) ||
        (document.webkitFullscreenElement && document.webkitFullscreenElement !== null) ||
        (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
        (document.msFullscreenElement && document.msFullscreenElement !== null);

    var docElm = document.documentElement;
    if (!isInFullScreen) {
        if (docElm.requestFullscreen) {
            docElm.requestFullscreen();
        } else if (docElm.mozRequestFullScreen) {
            docElm.mozRequestFullScreen();
        } else if (docElm.webkitRequestFullScreen) {
            docElm.webkitRequestFullScreen();
        } else if (docElm.msRequestFullscreen) {
            docElm.msRequestFullscreen();
        }
    } else {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
    }
}

And a simple case on how to use it :

<button onclick="fullscreen()">Toggle FullScreen</button>

You need to make sure that this is a short method called when the user does an action on the page. From what the documentation says, is this is a feature that requires a higher access mode, and thus you can not (at this time) automatically force fullscreen on things like when the page has loaded, or async events (unless they are events from a users action like Click), etc.