The Fullscreen API provides a standardized way to display content using the user's entire screen, removing all browser chrome and other application interfaces until fullscreen mode is deactivated. This creates an immersive experience ideal for media-heavy applications, interactive presentations, and games built with modern web development frameworks like Next.js.
Whether you're building a video streaming platform, an interactive presentation tool, or a browser-based game, the Fullscreen API enables you to deliver the immersive experience users expect. Unlike simply maximizing a browser window, true fullscreen mode completely removes browser chrome, toolbars, and system UI, allowing your content to command the user's complete attention. This guide covers everything from basic API methods to advanced React patterns, ensuring you can implement fullscreen functionality that works reliably across Chrome, Firefox, Safari, and Edge.
Everything you need to implement fullscreen functionality
Element.requestFullscreen()
Initiate fullscreen mode for any DOM element with a simple method call
Document.exitFullscreen()
Programmatically exit fullscreen mode and return to normal view
State Detection
Track fullscreen state with fullscreenElement and fullscreenEnabled properties
Event Handling
Respond to state changes with fullscreenchange and fullscreenerror events
Understanding the Fullscreen API
What the Fullscreen API Enables
The Fullscreen API provides a standardized way to display content using the user's entire screen, removing all browser chrome and other application interfaces until fullscreen mode is deactivated. This creates an immersive experience ideal for media-heavy applications, interactive presentations, and games.
Key capabilities include:
- Presenting any DOM element in true fullscreen mode
- Programmatically entering and exiting fullscreen
- Detecting current fullscreen state
- Styling fullscreen elements with CSS pseudo-selectors
Browser Support and Evolution
The Fullscreen API has evolved significantly since its introduction. Modern browsers support the standardized API, though vendor prefixes were historically required. Today, the unprefixed methods are widely supported across Chrome, Firefox, Safari, and Edge, making it a reliable choice for production applications.
Common Use Cases
-
Video players and streaming platforms: The most common use case, where users expect fullscreen playback for an optimal viewing experience. Platforms like YouTube and Netflix rely on this API for their video controls.
-
Image galleries and photography sites: Allow users to view images without distraction, often with zoom and pan capabilities in fullscreen mode. This is essential for photography portfolios and e-commerce product galleries.
-
Interactive presentations and slide decks: Create PowerPoint-like experiences directly in the browser, with smooth transitions between slides and the ability to present without venue equipment.
-
Browser-based games and simulations: Fullscreen mode provides the canvas space needed for immersive gameplay, removing browser chrome that could break the gaming experience.
-
Virtual tours and 360-degree content: Real estate listings, travel sites, and educational platforms use fullscreen to make panoramic content feel truly immersive.
-
Document viewers and presentation tools: PDF viewers and presentation tools use fullscreen to focus reader attention on the content without interface clutter.
Core API Methods and Properties
Requesting Fullscreen Mode
The Element.requestFullscreen() method initiates fullscreen mode for a specific element. This method must be called within a user gesture event handler (click, keypress, touch) or the browser will deny the request for security reasons.
Feature detection is essential for cross-browser compatibility. While modern browsers support the standard API, older Safari versions and Internet Explorer 11 require vendor prefixes. A robust implementation checks for each variant and provides fallback support as part of a comprehensive web development strategy.
1async function enterFullscreen(element) {2 try {3 if (element.requestFullscreen) {4 await element.requestFullscreen();5 } else if (element.webkitRequestFullscreen) {6 // Safari7 await element.webkitRequestFullscreen();8 } else if (element.msRequestFullscreen) {9 // IE1110 await element.msRequestFullscreen();11 }12 } catch (error) {13 console.error('Fullscreen request failed:', error);14 }15}Exiting Fullscreen Mode
The Document.exitFullscreen() method exits fullscreen mode. Note that this method is called on the document, not the element that was previously displayed in fullscreen. This design reflects the fact that the browser manages fullscreen at the document level--there can only be one fullscreen element at a time. When multiple elements attempt to enter fullscreen, the browser manages a stack, with newer elements appearing above older ones.
When exiting fullscreen, always use the document's exitFullscreen method rather than trying to call a method on the element itself. The browser handles the transition back to normal view and restores the previous document state.
1async function exitFullscreen() {2 try {3 if (document.exitFullscreen) {4 await document.exitFullscreen();5 } else if (document.webkitExitFullscreen) {6 await document.webkitExitFullscreen();7 } else if (document.msExitFullscreen) {8 await document.msExitFullscreen();9 }10 } catch (error) {11 console.error('Exit fullscreen failed:', error);12 }13}Checking Fullscreen State
Two properties provide information about the current fullscreen state:
Document.fullscreenElement: Returns the element currently displayed in fullscreen mode, ornullif no element is in fullscreenDocument.fullscreenEnabled: Returns a boolean indicating whether fullscreen mode is available in the current context
A utility function that combines these properties provides a complete picture of the fullscreen state, useful for conditionally rendering UI elements or making decisions about fullscreen features.
1function getFullscreenStatus() {2 const element = document.fullscreenElement;3 const isFullscreen = element !== null;4 const isAvailable = document.fullscreenEnabled;5 6 return {7 isFullscreen,8 isAvailable,9 element,10 elementTagName: element?.tagName || null,11 elementId: element?.id || null12 };13}14 15// Usage example16const status = getFullscreenStatus();17if (status.isFullscreen) {18 console.log(`Fullscreen element: #${status.elementId}`);19}Working with Fullscreen Events
The Fullscreen API provides two events for tracking state changes and handling errors. Understanding these events is crucial for building responsive fullscreen experiences that maintain UI consistency.
The fullscreenchange Event
The fullscreenchange event fires on the document when the document enters or exits fullscreen mode. This event doesn't indicate the direction of the change--your code must determine the current state by checking document.fullscreenElement. The event fires synchronously when the transition completes, allowing you to update your UI immediately.
The fullscreenerror Event
The fullscreenerror event fires when an error occurs during a fullscreen request. Common causes include requesting fullscreen outside a user gesture, attempting to fullscreen an iframe without proper permissions, or content restrictions in enterprise environments.
1// Listen for state changes2document.addEventListener('fullscreenchange', handleFullscreenChange);3 4function handleFullscreenChange() {5 const isFullscreen = document.fullscreenElement !== null;6 7 if (isFullscreen) {8 console.log('Entered fullscreen mode');9 // Update UI - hide normal controls, show fullscreen controls10 // Update analytics tracking11 // Adjust layout for fullscreen12 } else {13 console.log('Exited fullscreen mode');14 // Restore normal state15 // Update analytics with viewing time16 }17}18 19// Listen for errors20document.addEventListener('fullscreenerror', handleFullscreenError);21 22function handleFullscreenError(event) {23 console.error('Fullscreen error:', event);24 // Show user-friendly error message25 // Provide fallback experience if fullscreen unavailable26}Security Requirements and Best Practices
User Gesture Requirement
Browser security policies require fullscreen requests to originate from within a user-initiated event handler. This prevents malicious sites from forcing fullscreen mode and trapping users in an immersive experience.
Valid triggers:
- Click events on buttons or links
- Keypress events (certain keys like F for fullscreen)
- Touch events on mobile devices
- Form submission events
Invalid triggers:
- Page load or DOMContentLoaded
- setTimeout or setInterval callbacks
- Fetch completion handlers
- Any code not directly connected to user input
// CORRECT: User gesture context
document.getElementById('fullscreen-btn').addEventListener('click', () => {
videoElement.requestFullscreen();
});
// INCORRECT: Will fail - no user gesture
function startPresentation() {
videoElement.requestFullscreen(); // Request denied
}
iframe Permissions
Iframes must explicitly allow fullscreen content through the allowfullscreen attribute. Cross-origin iframes require the allow attribute with the fullscreen feature. Without these attributes, iframe content cannot trigger fullscreen mode.
<iframe
src="https://external-content.example.com"
allowfullscreen
allow="fullscreen"
></iframe>
Permissions Policy
Enterprise environments may block fullscreen through the Permissions Policy. The document.fullscreenEnabled property returns false when fullscreen is blocked. Always check this property and provide graceful degradation--perhaps a maximized modal instead of true fullscreen.
function setupFullscreenButton(button, element) {
if (!document.fullscreenEnabled) {
button.disabled = true;
button.title = 'Fullscreen is not available in your environment';
// Provide alternative: maximize within container
return;
}
button.addEventListener('click', () => {
if (document.fullscreenElement) {
document.exitFullscreen();
} else {
element.requestFullscreen();
}
});
}
User Experience Best Practices
Always inform users how to exit fullscreen mode, as not all users are familiar with keyboard shortcuts. Provide visible controls and mention ESC key or F11 in documentation. Handle unexpected exits gracefully--tab switches, navigation, or browser crashes should not break your application's state.
CSS Integration for Fullscreen Elements
The :fullscreen Selector
When an element is displayed in fullscreen mode, it matches the :fullscreen CSS pseudo-selector. This allows you to apply specific styles only when the element is in fullscreen mode, such as expanding to fill the viewport and adjusting layout for immersive viewing.
The ::backdrop Pseudo-Element
The ::backdrop pseudo-element styles the region behind fullscreen elements, visible when multiple elements enter fullscreen in a stacked manner. This is useful for creating visual depth, adding overlays, or ensuring a consistent background color behind your content.
Multiple Fullscreen Elements
When multiple elements enter fullscreen, they stack with newer elements on top. Each element's ::backdrop is visible behind elements above it, allowing for layered fullscreen experiences.
1/* Base styles for video container */2.video-container {3 width: 100%;4 max-width: 800px;5 margin: 0 auto;6 position: relative;7}8 9/* Additional styles when in fullscreen */10.video-container:fullscreen {11 width: 100vw;12 height: 100vh;13 max-width: none;14 display: flex;15 align-items: center;16 justify-content: center;17 background-color: #000;18}19 20/* Style the backdrop behind fullscreen content */21.video-player:fullscreen::backdrop {22 background-color: rgba(0, 0, 0, 0.95);23}24 25/* Fullscreen-specific controls visibility */26.video-controls {27 opacity: 0.3;28 transition: opacity 0.3s ease;29}30 31/* Show controls on hover or when in fullscreen */32.video-container:fullscreen .video-controls,33.video-container:hover .video-controls {34 opacity: 1;35}Implementing Fullscreen in Modern Frameworks
React Implementation
React components can use hooks to manage fullscreen state with proper lifecycle handling. The useFullscreen hook provides a clean, reusable interface for common fullscreen operations, encapsulating all the complexity of event listeners and state management. This pattern is especially valuable in larger React applications where fullscreen features may be used across multiple components.
Next.js Considerations
In Next.js applications, the Fullscreen API is only available on the client side because it depends on the browser's window object. Always wrap fullscreen logic in useEffect or check for typeof window !== 'undefined' before accessing any Fullscreen API properties. The 'use client' directive is required for components that use the API. For more Next.js development patterns, explore our comprehensive web development services.
1import { useState, useCallback, useRef, useEffect } from 'react';2 3export function useFullscreen(elementRef) {4 const [isFullscreen, setIsFullscreen] = useState(false);5 6 useEffect(() => {7 const element = elementRef.current;8 if (!element) return;9 10 const handleChange = () => {11 setIsFullscreen(document.fullscreenElement === element);12 };13 14 const handleError = (e) => {15 console.error('Fullscreen error:', e);16 };17 18 document.addEventListener('fullscreenchange', handleChange);19 document.addEventListener('fullscreenerror', handleError);20 21 return () => {22 document.removeEventListener('fullscreenchange', handleChange);23 document.removeEventListener('fullscreenerror', handleError);24 };25 }, [elementRef]);26 27 const enterFullscreen = useCallback(async () => {28 const element = elementRef.current;29 if (element?.requestFullscreen) {30 await element.requestFullscreen();31 }32 }, [elementRef]);33 34 const exitFullscreen = useCallback(async () => {35 if (document.exitFullscreen) {36 await document.exitFullscreen();37 }38 }, []);39 40 const toggleFullscreen = useCallback(() => {41 if (isFullscreen) {42 exitFullscreen();43 } else {44 enterFullscreen();45 }46 }, [isFullscreen, enterFullscreen, exitFullscreen]);47 48 return { isFullscreen, enterFullscreen, exitFullscreen, toggleFullscreen };49}1'use client';2 3import { useState, useEffect, useCallback, useRef } from 'react';4 5export function FullscreenImage({ src, alt }) {6 const containerRef = useRef(null);7 const [isFullscreen, setIsFullscreen] = useState(false);8 9 useEffect(() => {10 const container = containerRef.current;11 if (!container) return;12 13 const handleChange = () => {14 setIsFullscreen(document.fullscreenElement === container);15 };16 17 document.addEventListener('fullscreenchange', handleChange);18 return () => document.removeEventListener('fullscreenchange', handleChange);19 }, []);20 21 const toggleFullscreen = useCallback(async () => {22 const container = containerRef.current;23 if (!container) return;24 25 if (document.fullscreenElement) {26 await document.exitFullscreen();27 } else {28 await container.requestFullscreen();29 }30 }, []);31 32 return (33 <div34 ref={containerRef}35 className={isFullscreen ? 'fullscreen-mode' : ''}36 style={{ position: 'relative' }}37 >38 <img39 src={src}40 alt={alt}41 style={{ maxWidth: '100%', height: 'auto' }}42 />43 <button44 onClick={toggleFullscreen}45 style={{46 position: 'absolute',47 top: 10,48 right: 10,49 padding: '8px 16px',50 background: 'rgba(0,0,0,0.7)',51 color: 'white',52 border: 'none',53 borderRadius: 4,54 cursor: 'pointer'55 }}56 >57 {isFullscreen ? 'Exit Fullscreen' : 'Fullscreen'}58 </button>59 </div>60 );61}Performance Considerations
Rendering Performance
When entering fullscreen mode, browsers typically remove browser chrome, recalculate layout for the fullscreen element, potentially trigger hardware acceleration, and change compositing strategies. These changes can impact rendering performance, especially for complex layouts with many elements.
Animation and Transitions
Fullscreen transitions can be resource-intensive. Consider these optimizations:
-
Use CSS transforms for smooth animations: Transforms are GPU-accelerated and won't trigger layout recalculations. Use
transform: scale()ortransform: translate()instead of changing width/height properties. -
Avoid layout thrashing during transition: Reading layout properties like
offsetHeightduring animations forces synchronous reflow, causing jank. Batch reads before starting animations. -
Consider will-change property: For elements that will animate, add
will-change: transformto hint the browser to optimize ahead of time. -
Test on lower-end devices: Performance characteristics vary significantly across devices. Test on representative hardware to establish a performance baseline.
Memory Considerations
Fullscreen media (especially video) consumes significant memory at higher resolutions. Implement proper preload strategies, cleanup on exit, and quality adjustment for fullscreen playback to prevent memory-related issues during extended sessions.
1async function toggleFullscreenWithPerformance(element) {2 const isAlreadyFullscreen = document.fullscreenElement === element;3 4 // Use requestAnimationFrame for smooth transitions5 return new Promise((resolve) => {6 requestAnimationFrame(async () => {7 try {8 if (isAlreadyFullscreen) {9 await document.exitFullscreen();10 } else {11 await element.requestFullscreen();12 }13 resolve(true);14 } catch (error) {15 console.error('Fullscreen operation failed:', error);16 resolve(false);17 }18 });19 });20}21 22// For video: adjust quality on fullscreen entry23document.addEventListener('fullscreenchange', () => {24 const video = document.querySelector('video');25 if (document.fullscreenElement && video) {26 // Increase quality for fullscreen viewing27 video.setAttribute('quality', 'high');28 }29});Common Patterns and Use Cases
Video Player Fullscreen
The most common fullscreen use case involves video elements with custom controls. A well-designed fullscreen video player handles state transitions, keyboard events (Escape key, F key for toggle), and provides clear exit controls. The player class pattern encapsulates all fullscreen logic in a reusable component.
Image Gallery Fullscreen
Image galleries often use fullscreen for immersive viewing, with navigation controls, smooth transitions between images, and keyboard navigation. A gallery fullscreen viewer typically creates an overlay element that enters fullscreen, providing next/previous controls and image metadata.
1class FullscreenVideoPlayer {2 constructor(videoElement, containerElement) {3 this.video = videoElement;4 this.container = containerElement;5 this.setupEventListeners();6 }7 8 setupEventListeners() {9 // Toggle on button click10 const toggleBtn = document.getElementById('fs-toggle');11 if (toggleBtn) {12 toggleBtn.addEventListener('click', () => this.toggle());13 }14 15 // Handle escape key - some browsers need help16 document.addEventListener('keydown', (e) => {17 if (e.key === 'Escape' && document.fullscreenElement === this.container) {18 this.exit();19 }20 // F key for toggle21 if (e.key === 'f' || e.key === 'F') {22 this.toggle();23 }24 });25 26 // Track state changes27 document.addEventListener('fullscreenchange', () => this.onStateChange());28 }29 30 async toggle() {31 if (document.fullscreenElement === this.container) {32 await this.exit();33 } else {34 await this.enter();35 }36 }37 38 async enter() {39 if (this.container.requestFullscreen) {40 await this.container.requestFullscreen();41 }42 }43 44 async exit() {45 if (document.exitFullscreen) {46 await document.exitFullscreen();47 }48 }49 50 onStateChange() {51 const isFullscreen = document.fullscreenElement === this.container;52 // Update UI - show/hide fullscreen controls53 // Update analytics tracking54 // Adjust video quality if needed55 }56}1function setupGalleryFullscreen(galleryElement) {2 const images = galleryElement.querySelectorAll('.gallery-image');3 let currentIndex = 0;4 5 images.forEach((img, index) => {6 img.addEventListener('click', () => {7 currentIndex = index;8 openFullscreenGallery(currentIndex);9 });10 });11 12 async function openFullscreenGallery(startIndex) {13 const viewer = createFullscreenViewer(images, startIndex);14 document.body.appendChild(viewer);15 16 try {17 await viewer.requestFullscreen();18 } catch (error) {19 console.error('Gallery fullscreen failed:', error);20 // Fallback: show in modal without fullscreen21 showGalleryModal(viewer);22 }23 }24 25 function createFullscreenViewer(images, startIndex) {26 const viewer = document.createElement('div');27 viewer.className = 'gallery-viewer';28 viewer.innerHTML = `29 <img src="${images[startIndex].src}" />30 <button class="prev">Previous</button>31 <button class="next">Next</button>32 <button class="close">Close</button>33 `;34 return viewer;35 }36}Common Fullscreen Issues and Solutions
Conclusion
The Fullscreen API provides a powerful mechanism for creating immersive web experiences that rival native applications. When implementing fullscreen functionality, prioritize these key principles:
- Security compliance through proper user gesture handling--always trigger fullscreen from direct user interaction events
- Graceful degradation when fullscreen is unavailable--provide fallback experiences for restricted environments
- Clear user interface for exiting fullscreen mode--users should never feel trapped
- Cross-browser compatibility through feature detection and vendor prefix fallbacks
- Performance optimization for smooth transitions and efficient resource usage
By following these patterns and best practices, you can create compelling fullscreen experiences that work reliably across all modern browsers while maintaining security and performance standards. Whether you're building video players, image galleries, presentations, or interactive applications, the Fullscreen API delivers the immersive canvas your content deserves.
For more web development insights, explore our React Hooks guide or learn about TypeScript with Node.js for building robust fullstack applications.