JavaScript Fullscreen API

Among web applications one the basic features you might need is a fullscreen mode.

It's surprisingly simple how to achieve it using pure and simple JavaScript.

The JavaScript

To turn on the fullscreen mode you can call this function using an event handler or any other method of your choice.

function do_fullscreen(element) { if(element.requestFullscreen) { element.requestFullscreen(); } else if(element.mozRequestFullScreen) { element.mozRequestFullScreen(); } else if(element.webkitRequestFullscreen) { element.webkitRequestFullscreen(); } else if(element.msRequestFullscreen) { element.msRequestFullscreen(); } }
Code language: JavaScript (javascript)

This will turn it on for the whole document:

Code language: JavaScript (javascript)

In the other hand, if you want to turn off the fullscreen mode call this function:

function undo_fullscreen() { if(document.exitFullscreen) { document.exitFullscreen(); } else if(document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if(document.webkitExitFullscreen) { document.webkitExitFullscreen(); } }
Code language: JavaScript (javascript)


I had a blackground-color on my body element but when I turned on the Fullscreen it was showing just a rectangle with that color.

You can specify styles for the fullscreen window mode. In my case I needed to specify the background-color again:

:-webkit-full-screen { background: #3498db; } :-moz-full-screen { background: #3498db; } :-ms-fullscreen { background: #3498db; } :full-screen { background: #3498db; } :fullscreen { background: #3498db; }
Code language: CSS (css)


View Demo

More on the fullscreen API on the MDN site.

Leave a Reply

Your email address will not be published. Required fields are marked *