Checkout my Getting Started with React video course on Skillshare. It is 100% free.

Making an element fullscreen with Javascript

I just discovered there is a new toy we can play with as web developers. The fullscreen API 😎. Let's see what it is about.

How to make an element fullscreen using Javascript?

Making an element fullscreen with JS is pretty straightforward. After we get its reference we just need to call requestFullscreen().

const el = document.getElementById('element'); 
el.requestFullscreen();

Keep in mind that there may be a case to use prefixes for some browsers. More details here.

How to close a fullscreen element?

In order to revert a fullscreen element to its initial state we just need to call exitFullscreen() on the element.

How to track if an element is fullscreen or not?

We have two options to track if there is a full-screen element. The first one will be to use the fullscreenchange event.

document.addEventListener('fullscreenchange', () => {
  if (document.fullscreenElement)
    alert('We are in fullscreen mode !!!')
  else
    alert('No fullscreen here !!!')
})

The second one is to use the return a promise from requestFullscreen. However, keep in mind that this one does not work in some browsers 😞, so it may be a safer bet to use the fullscreenchange event.

el.addEventListener('click', () => {
    const p = el.mozRequestFullScreen();
    p.then(() => {console.log('full screen')});
});

How do we style a fullscreen element?

If you want your element to look different when it is fullscreen, we have the :fullscreen pseudo selector:

.element:fullscreen {
    // rules here
}

And here is a full codepen to play with the fullscreen API:

See the Pen
FLS
by JS Craft (@js-craft)
on
CodePen.