🎁 Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

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.

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

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