Skip to content

Instantly share code, notes, and snippets.

@demonixis
Created March 18, 2013 16:07
Show Gist options
  • Save demonixis/5188326 to your computer and use it in GitHub Desktop.
Save demonixis/5188326 to your computer and use it in GitHub Desktop.
A simple function to toggle fullscreen in JavaScript. It work well on Firefox and Webkit browsers.
/**
* Toggle fullscreen function who work with webkit and firefox.
* @function toggleFullscreen
* @param {Object} event
*/
function toggleFullscreen(event) {
var element = document.body;
if (event instanceof HTMLElement) {
element = event;
}
var isFullscreen = document.webkitIsFullScreen || document.mozFullScreen || false;
element.requestFullScreen = element.requestFullScreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || function () { return false; };
document.cancelFullScreen = document.cancelFullScreen || document.webkitCancelFullScreen || document.mozCancelFullScreen || function () { return false; };
isFullscreen ? document.cancelFullScreen() : element.requestFullScreen();
}
@justingolden21
Copy link

You can use "documentElement" instead of "body" to avoid the black screen of the html body.

Works for me

@JoshuaCarroll
Copy link

Brilliant.

@vinnycrazzy
Copy link

simply incredible!

@OttCS
Copy link

OttCS commented Sep 6, 2023

Great work! Here's a version that uses ES6 features for more streamlined code:

function toggleFullscreen(view = document.body) {
    view.requestFullScreen = view.requestFullScreen || view.webkitRequestFullScreen || view.mozRequestFullScreen || function () { return false };
    document.cancelFullScreen = document.cancelFullScreen || document.webkitCancelFullScreen || document.mozCancelFullScreen || function () { return false };
    (document.webkitIsFullScreen || document.mozFullScreen || false) ? document.cancelFullScreen() : view.requestFullScreen();
}

We can trust the person calling the function to either pass in no view element and wants the body to go fullscreen, or they'll pass in an appropriate HTMLElement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment