JAVASCRIPT

Toggle Fullscreen Mode for Any HTML Element

Control the browser's Fullscreen API to make a specific HTML element or the entire page expand to fullscreen mode with a JavaScript function.

function toggleFullscreen(element) {
    if (!document.fullscreenElement) {
        // If no element is in fullscreen, request fullscreen for the given element
        if (element.requestFullscreen) {
            element.requestFullscreen();
        } else if (element.mozRequestFullScreen) { /* Firefox */
            element.mozRequestFullScreen();
        } else if (element.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
            element.webkitRequestFullscreen();
        } else if (element.msRequestFullscreen) { /* IE/Edge */
            element.msRequestFullscreen();
        }
    } else {
        // If an element is in fullscreen, exit fullscreen mode
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.mozCancelFullScreen) { /* Firefox */
            document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) { /* Chrome, Safari & Opera */
            document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) { /* IE/Edge */
            document.msExitFullscreen();
        }
    }
}

// Usage example:
// const myElement = document.getElementById('myVideoPlayer');
// document.getElementById('fullscreenButton').addEventListener('click', () => {
//     toggleFullscreen(myElement);
// });
// Or for the entire page:
// toggleFullscreen(document.documentElement);
How it works: This snippet demonstrates how to toggle fullscreen mode for any specified HTML element using the Fullscreen API. The `toggleFullscreen` function first checks if any element is currently in fullscreen (`document.fullscreenElement`). If not, it requests fullscreen for the provided element using `requestFullscreen()` (and vendor-prefixed versions for broader compatibility). If an element is already in fullscreen, it calls `document.exitFullscreen()` to revert to normal view. This is highly useful for media players, image galleries, or interactive applications where an immersive user experience is desired.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs