Make Your Elements Full With requestFullscreen
Let's put it out there. This isn't one you're going to need often. But, it's cool to know about. There are so many neat native APIs that we often never use or overlook.
I only looked this one up because of a tweet thread Kent started
Check out this tweet!
And the React hook useFull
was born! 😅
Check out this pen by Jhey (@jh3y) on CodePen.
A React hook for making an element fullscreen.
But, this made me take a closer look at the method requestFullscreen
from the Element API.
For those in camp TL;DR, you can make an element fullscreen with requestFullscreen
(There are prefixes).
The request requires some form of user gesture. You can't request fullscreen without it.
Have a play with this demo!
Check out this pen by Jhey (@jh3y) on CodePen.
Why? permalink
True. It's not something you'll use often. A common use case? Displaying media, documents, etc. Think YouTube videos, etc.
How? permalink
It's as straightforward as
const makeFullscreen = () => {
element.requestFullscreen()
}
That needs to happen as the result of a user gesture. You might make the request as a result of clicking a button for example.
BUTTON.addEventListener('click', makeFullscreen)
The cool thing is that you can make anything fullscreen. As long as it's not a dialog
.
Detect Changes permalink
How do you detect when you're in fullscreen mode? The method returns a Promise
. But, not in all browsers 🤦♂️
The most compatible way currently is to listen to a fullscreenchange
event on the document
. Then check for the existence of document.fullscreenElement
.
document.addEventListener('fullscreenchange', () => {
if (document.fullscreenElement)
console.info('We are fullscreen!!!')
else
console.info('Do nothing...')
})
This gives you a neat hook to make changes to elements. You could apply different styles for example. In the React example above, I trigger an animation when the element goes into fullscreen mode. I do this by adding/removing a class on fullscreenchange
.
Leaving permalink
When you want to get out of fullscreen mode
document.exitFullscreen()
That's It! permalink
That's all there is to it.
The fun thing here is, what could you make with it? What kinda experience could you offer up to people with it? Where does your imagination take you?
What other cool browser APIs are out there to play with?
For example, in this demo, particle animations happen upon button click. It's like a "mock" screensaver you could provide your users!
NOTE:: There's a reason you can't create fullscreen screensavers that would show after some inactivity. One reason. Think of the popups!
Check out this pen by Jhey (@jh3y) on CodePen.
Stay awesome!