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 *

Home Screencasts Best of Newsletter Search X

πŸ“– 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X