LEARNING OBJECTIVES โต
- Implement
element.requestFullscreen()across different DOM element types (<div>,<video>,<canvas>,document.documentElement). - Handle asynchronous Promise resolution and capture security rejection errors gracefully.
- Configure
FullscreenOptionsusing thenavigationUIdictionary parameter ('auto','show','hide'). - Integrate screen orientation locks (
screen.orientation.lock()) on mobile devices during fullscreen transitions.
๐ The Mental Model & Story (Intuitive Foundation)
Imagine a high-end presentation podium equipped with multiple projection spotlights.
On the stage, you have an entire orchestra, a choir, and a solo pianist. When the pianist begins their solo, the lighting director doesn't just illuminate the entire stage at maximum brightness. Instead, they activate a high-powered spotlight directly focused on the pianist and piano, dimming everything else in the hall.
ELEMENT PROMOTION MENTAL MODEL
+-------------------------------------------------------------------------------+
| STAGE (The Web Document) |
| |
| [Header / Brand Bar] [Sidebar Navigation] [Footer Copyright] |
| |
| +--------------------------------+ |
| | TARGET ELEMENT (e.g. #player) | |
| | | |
| | requestFullscreen() Called | |
| +--------------------------------+ |
+-------------------------------------------------------------------------------+
|
v (Spotlight Activated)
+===============================================================================+
| PHYSICAL DISPLAY (100% Screen Dimensions: 1920x1080 / 3840x2160) |
| |
| +------------------------------------------------+ |
| | | |
| | PROMOTED TARGET ELEMENT | |
| | (#player) | |
| | | |
| +------------------------------------------------+ |
| |
+===============================================================================+
When you invoke element.requestFullscreen(), you are instructing the browser's compositor to shine its spotlight exclusively on that target element. Whether that element is a 300x200 pixel video preview or a 3D WebGL canvas, the browser elevates it into the display plane, providing the exact pixel coordinates of the host screen.
Technical Deep Dive & Specifications
The requestFullscreen() Method Signature
element.requestFullscreen(options?: FullscreenOptions): Promise<void>
Under the WHATWG Fullscreen API specification, requestFullscreen() returns a standard JavaScript Promise:
- Resolves with
undefined: When the browser successfully switches the display mode and promotes the element to the Top Layer. - Rejects with a
TypeError: When the request is denied due to lack of user gesture, iframe permission restrictions, or window state constraints.
The FullscreenOptions Dictionary & navigationUI
When invoking requestFullscreen(), you can pass an optional dictionary containing configuration parameters for the host operating system's navigation UI:
const options = {
navigationUI: 'auto' // 'auto' | 'show' | 'hide'
};
await element.requestFullscreen(options);
+-------------------------------------------------------------------------------+
| `navigationUI` OPTIONS MATRIX |
+-------------------+-----------------------------------------------------------+
| Value | Behavior & Operating System Hints |
+-------------------+-----------------------------------------------------------+
| `'auto'` (Default)| The browser decides based on device context. On mobile, |
| | it typically auto-hides navigation controls until swipe. |
| | |
| `'show'` | Explicitly requests that navigation UI (e.g. software |
| | back buttons, home bars, or URL bars) remain accessible. |
| | |
| `'hide'` | Explicitly requests that all software navigation elements |
| | be hidden for complete, uninterrupted immersion. |
+-------------------+-----------------------------------------------------------+
[!NOTE]
navigationUIis a user agent hint. The host operating system (especially iOS and Android) retains ultimate authority over whether home bars or system gesture zones can be fully suppressed.
Asynchronous Execution Pipeline
When element.requestFullscreen() is executed, the browser performs the following sequence of internal validation steps:
[1. User Gesture Check] ===(No Gesture)===> [Reject Promise (TypeError)]
|
(Valid)
v
[2. Permission Policy Check] ===(Iframe Blocked)===> [Reject Promise (TypeError)]
|
(Allowed)
v
[3. Promote to Top Layer]
|
v
[4. Resize Viewport & Dispatch 'fullscreenchange']
|
v
[5. Resolve Promise (void)]
Pairing with Screen Orientation API
For immersive video players and mobile games, entering fullscreen is often paired with locking the mobile device into landscape orientation:
async function launchImmersiveGame(gameCanvas) {
try {
// 1. Enter fullscreen
await gameCanvas.requestFullscreen({ navigationUI: 'hide' });
// 2. Lock screen orientation to landscape (if supported)
if (screen.orientation && screen.orientation.lock) {
await screen.orientation.lock('landscape');
}
} catch (err) {
console.warn('Fullscreen/Orientation request failed:', err);
}
}
๐ป Interactive Code Playground
Starter Code
Line-by-Line Code Breakdown
- Line 115โ124 (
options-panel): Provides a dynamic configuration dropdown allowing users to toggle between'auto','hide', and'show'for thenavigationUIdictionary. - Line 160โ165 (
options): Constructs the options object{ navigationUI: 'auto' | 'hide' | 'show' }to pass as the argument torequestFullscreen(). - Line 169 (
await targetElement.requestFullscreen(options)): Invokes the method on the specific targeted DOM card, returning a Promise that resolves when the browser successfully promotes the element into the Top Layer. - Line 172โ174 (
catch (err)): Traps errors if the browser denies the request or if an unsupported option configuration triggers a failure.
Expected Browser Render Output
- The user sees three interactive cards: Video Player, Game Canvas, and Analytics Dashboard.
- Clicking "Fullscreen Video" causes only the Video Player card to expand to the full width and height of the display.
- The surrounding web page, header, and other cards are covered by the browser's backdrop layer.
- Pressing
Escaperestores the card to its original size in the gallery grid.
๐๏ธ Hands-On Exercise
๐ฏ The Challenge: Implement an Element-Specific Fullscreen Gallery Modal
Instructions:
- Create an image gallery with 2 image thumbnail containers.
- When the user clicks an image container, promote that specific container to fullscreen mode.
- Attach a custom Promise timeout safeguard: if the
requestFullscreen()Promise does not resolve within 1500ms (or encounters an error), display an alert fallback. - Include a status badge inside the active element that dynamically reads
"FULLSCREEN MODE ACTIVE"only when expanded.
๐ Starter Code Sandbox
โ ๏ธ Common Pitfalls
- Invoking on Unsupported Elements in Legacy iOS: Calling
requestFullscreen()on arbitrary<div>elements on iPhone Safari historically failed (Safari on iOS historically only allowed<video>.webkitEnterFullscreen()). Always provide a fallback. - Assuming Synchronous Execution:
requestFullscreen()is asynchronous. Code placed immediately after the call may execute before the element has actually resized or entered the Top Layer. Alwaysawaitthe Promise or listen tofullscreenchange. - Passing Non-Standard Option Properties: Providing unsupported keys inside the
FullscreenOptionsobject will be ignored by conforming browsers, but may trigger validation issues in strict TypeScript setups.
๐ก Pro Tips
- Handle Multi-Monitor Setups: The Fullscreen API promotes the element to the screen hosting the browser window. For multi-monitor presentation software, pair this with the Window Management API (
getScreenDetails()) to query multi-screen coordinates. - Lock Screen Orientation Responsibly: When calling
screen.orientation.lock('landscape'), always wrap it in a separatetry/catch, as desktop browsers and unsupported devices throw anunsupportederror without breaking the fullscreen transition.
๐ Key Takeaways
element.requestFullscreen()promotes a specific DOM node into the browser's Top Layer.- The method returns a standard JavaScript Promise that resolves upon visual promotion or rejects on permission failure.
- The
navigationUIoption accepts'auto','show', or'hide'to advise the browser on how to treat system bars. - Combining
requestFullscreen()withscreen.orientation.lock()creates console-quality mobile gaming and media experiences. - --