Fullscreen API
Fullscreen API provides many useful methods and properties to enter or exit fullscreen mode. Web bar at the top and window bar at the bottom will be hidden in Fullscreen mode.
Open Fullscreen
The requestFullscreen()
in HTML element is a function consisting of Promise to make element fullscreen mode.
Document: Full page
const openFullscreen = async () => {
if (!document.fullscreenElement) {
if (document.documentElement.requestFullscreen) {
await document.documentElement.requestFullscreen()
}
}
}
The fullscreenElement
instance property allows to get current HTML Element displayed in fullscreen mode.
If this is null
, the document is not in fullscreen mode. Shortly, it's used to check whether document is in fullscreen mode.
Element
const openFullscreen = async (element: HTMLElement) => {
if (element.requestFullscreen) {
await element.requestFullscreen()
}
}
You can make specific element space fullscreen mode.
In addition, pressing F11
key allows to enter fullscreen mode.
Close Fullscreen
You also can exit fullscreen mode by pressing ESC
or F11
key.
const closeFullscreen = async () => {
if (document.fullscreenElement) {
if (document.exitFullscreen) {
await document.exitFullscreen()
}
}
}
The requestFullscreen()
in HTML element is used to exit Fullscreen mode. If it's not in fullscreen mode, it won't be worked.
CSS
CSS style in Fullscreen mode can be modified.
/* Safari */
:-webkit-full-screen {
background-color: green;
}
/* IE11 */
:-ms-fullscreen {
background-color: green;
}
/* Standard syntax */
:fullscreen {
background-color: green;
}
document.fullscreenEnabled
property.
The document.fullscreenEnabled
property returns boolean type. If fullscreen mode is not available, it returns false. Otherwise false.
Events
The Fullscreen API detects two events.
fullscreenchange
in Element
document.documentElement.addEventListener('fullscreenchange', handleFullscreenChange)
document.documentElement.removeEventListener('fullscreenchange', handleFullscreenChange)
const handleFullscreenChange = (event: HTMLElementEventMap['fullscreenchange']) => {
// Logic
}
The fullscreenchange
event is fired when fullscreen mode is switched successfully.
fullscreenerror
in Element
document.documentElement.addEventListener('fullscreenerror', handleFullscreenError)
document.documentElement.removeEventListener('fullscreenerror ', handleFullscreenError)
const handleFullscreenError = (event: HTMLElementEventMap['fullscreenerror']) => {
// Logic
}
The fullscreenerror
event is fired when fullscreen mode cannot be switched.