Skip to content

Instantly share code, notes, and snippets.

@demonixis
Created March 18, 2013 16:07
Show Gist options
  • Select an option

  • Save demonixis/5188326 to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown

Good work. Thanks

@weholt

weholt commented Sep 24, 2018

Copy link
Copy Markdown

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

@navgg

navgg commented Sep 27, 2018

Copy link
Copy Markdown

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

@MoWafa

MoWafa commented Nov 16, 2018

Copy link
Copy Markdown

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

@justingolden21

Copy link
Copy Markdown

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

Works for me

@JoshuaCarroll

Copy link
Copy Markdown

Brilliant.

@vinnycrazzy

Copy link
Copy Markdown

simply incredible!

@OttCS

OttCS commented Sep 6, 2023

Copy link
Copy Markdown

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