Snippet - toggleFullscreen()

Last updated on Thursday, February 27th, 2020 @ 2:35PM.
The native function that your code will need to call to enter, exit or toggle fullscreen depends on the browser that you are using. For instance to check if the screen is currently being shown in fullscreen mode you could need one of the following depending on the browser:
  • document.fullscreenElement
  • document.msFullscreenElement
  • document.mozFullScreenElement
  • document.webkitFullscreenElement
If one of the above values is a non-null and non-undefined then it will be the element that is being viewed in fullscreen. Now if you want to enter fullscreen mode you will want to call one of the following functions:
  • document.documentElement.requestFullscreen() (or use targetElement.requestFullscreen() for a specific element)
  • document.documentElement.msRequestFullscreen() (or use targetElement.msRequestFullscreen() for a specific element)
  • document.documentElement.mozRequestFullScreen() (or use targetElement.mozRequestFullScreen() for a specific element)
  • document.documentElement.webkitRequestFullscreen() (or use targetElement.webkitRequestFullscreen() for a specific element)
Once again, depending on the browser, you may need to use one of the following functions to exit fullscreen mode:
  • document.exitFullscreen()
  • document.msExitFullscreen()
  • document.mozCancelFullScreen()
  • document.webkitExitFullscreen()

All-in-one toggleFullscreen() Function

Of course, determining which browser the user is using is not the best way to figure out which code path to take. Instead it is always best to do feature testing. For this reason I developed the following toggleFullscreen() function which will do the feature test for you and then carry out the desired code:

Parameters

This function can take two optional parameters:
  1. {Element|undefined|null} opt_elem
    Optional. The element that should be targeted for fullscreen viewing.
  2. {?boolean=} opt_value
    Optional. If not given or undefined or null fullscreen will simply be toggled. If truthy the element will be set to fullscreen. If falsy and is not undefined or null fullscreen will be turned off if it is on.

Returns

{boolean|undefined}
If possible returns a boolean indicating if upon calling the function, an element was in fullscreen mode.

Examples

Using this function is very simple. Here are some buttons that you can click on to see the function in action:


Final Words

As you may have noticed, there is no advantage to calling toggleFullscreen(element, false). Whenever exiting fullscreen mode the function simply ignores the value passed in as the target element.
Please feel free to use this code in your own projects. The function should work in all modern browsers. As always, happy coding! 😎