Skip to content

Instantly share code, notes, and snippets.

@demonixis
Created March 18, 2013 16:07
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • 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();
}
@odysseus55
Copy link

Good work. Thanks

@weholt
Copy link

weholt commented Sep 24, 2018

It works great, but my background turns black. Any ways to avoid that?

@navgg
Copy link

navgg commented Sep 27, 2018

Quick fix for black background in chrome
* { background-color: white; }

@MoWafa
Copy link

MoWafa commented Nov 16, 2018

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

@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