๐Ÿ–ฅ๏ธ Chapter 54: The Fullscreen API

Entering Fullscreen with requestFullscreen()

Master element targeting, Promise-based fullscreen promotion, and configuring navigation UI preferences.

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 FullscreenOptions using the navigationUI dictionary parameter ('auto', 'show', 'hide').
  • Integrate screen orientation locks (screen.orientation.lock()) on mobile devices during fullscreen transitions.
๐ŸŽฌ INTERACTIVE VISUAL PIPELINE Core Architecture Simulation
๐ŸŒ
1. Input
Directives & Tags
โš™๏ธ
2. Parse
Tokenizer & AST
๐ŸŒณ
3. Layout
Box Model & Flow
๐ŸŽจ
4. Render
GPU Paint & Composite
PHASE 1: INPUT & DIRECTIVES
Browser receives declarative markup stream, parsing tag tokens and initializing component state.

๐Ÿ“– 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] navigationUI is 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 the navigationUI dictionary.
  • Line 160โ€“165 (options): Constructs the options object { navigationUI: 'auto' | 'hide' | 'show' } to pass as the argument to requestFullscreen().
  • 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

  1. The user sees three interactive cards: Video Player, Game Canvas, and Analytics Dashboard.
  2. Clicking "Fullscreen Video" causes only the Video Player card to expand to the full width and height of the display.
  3. The surrounding web page, header, and other cards are covered by the browser's backdrop layer.
  4. Pressing Escape restores the card to its original size in the gallery grid.

SYS: ACTIVE
HULL: 98%
CORE: STABLE
NET: ONLINE
HTML STARSHIP CODE TERMINAL playground.html
LIVE RENDER & DIAGNOSTICS CORE TEMP: 45ยฐC
INSPECTING DOM: VALID
TAGS: SCANNING...

๐Ÿ‹๏ธ Hands-On Exercise

๐ŸŽฏ The Challenge: Implement an Element-Specific Fullscreen Gallery Modal

Instructions:

  1. Create an image gallery with 2 image thumbnail containers.
  2. When the user clicks an image container, promote that specific container to fullscreen mode.
  3. Attach a custom Promise timeout safeguard: if the requestFullscreen() Promise does not resolve within 1500ms (or encounters an error), display an alert fallback.
  4. Include a status badge inside the active element that dynamically reads "FULLSCREEN MODE ACTIVE" only when expanded.

๐Ÿ Starter Code Sandbox

SYS: ACTIVE
HULL: 98%
CORE: STABLE
NET: ONLINE
STARTER CODE SANDBOX exercise.html
LIVE RENDER & DIAGNOSTICS CORE TEMP: 45ยฐC
INSPECTING DOM: VALID
TAGS: SCANNING...

โš ๏ธ Common Pitfalls

  1. 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.
  2. 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. Always await the Promise or listen to fullscreenchange.
  3. Passing Non-Standard Option Properties: Providing unsupported keys inside the FullscreenOptions object will be ignored by conforming browsers, but may trigger validation issues in strict TypeScript setups.

๐Ÿ’ก Pro Tips

  1. 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.
  2. Lock Screen Orientation Responsibly: When calling screen.orientation.lock('landscape'), always wrap it in a separate try/catch, as desktop browsers and unsupported devices throw an unsupported error 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 navigationUI option accepts 'auto', 'show', or 'hide' to advise the browser on how to treat system bars.
  • Combining requestFullscreen() with screen.orientation.lock() creates console-quality mobile gaming and media experiences.
  • --
โญ LEARN: HTML ๐ŸŒŸ โš”๏ธ QUIZ BATTLE ARENA // ACTIVE
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 1 / 3

What does element.requestFullscreen() return in modern conforming browsers?

Question 1 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 2 / 3

Which value for navigationUI requests the browser to hide software home indicators and system navigation bars if allowed by the OS?

Question 2 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 3 / 3

If a user clicks a button that runs await div.requestFullscreen(), what happens to sibling elements on the page?

Question 3 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP