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();
  }
}

This will turn it on for the whole document:

do_fullscreen(document.documentElement);

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();
  }
}

The CSS

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;
}

View Demo

More on the fullscreen API on the MDN site.

No comments yet, leave yours!

Leave a Reply

Add <code> Some Code </code> by using this tags.