W3docs

JavaScript Fullscreen API

In the realm of web development, engaging user experiences are paramount, and the JavaScript Fullscreen API plays a crucial role in achieving this. This

Introduction to the JavaScript Fullscreen API

In the realm of web development, engaging user experiences are paramount, and the JavaScript Fullscreen API plays a crucial role in achieving this. This powerful tool allows developers to programmatically request fullscreen display of an element, significantly enhancing the viewing experience for media-rich applications, games, and other interactive content.

Enabling Fullscreen Mode in JavaScript

To enable fullscreen mode in JavaScript, developers use the requestFullscreen method. This method is part of the Fullscreen API and is applied to any DOM element you wish to display in fullscreen. Note that the API requires a user gesture (such as a click) to trigger, which is why it is typically called inside an event handler. Here’s how to use this method effectively:


<div id="main-content">
    <button id="fs-btn">Go Fullscreen</button>
    <div id="video-container">
        <!-- Your content like a video or interactive media -->
    </div>
</div>

<script>
const element = document.getElementById("video-container");
const btn = document.getElementById("fs-btn");

btn.addEventListener("click", function() {
    if (document.fullscreenEnabled) {
        element.requestFullscreen().catch(err => {
            console.error(`Error attempting to enable fullscreen: ${err.message}`);
        });
    } else {
        console.log("Fullscreen API is not supported in this browser.");
    }
});
</script>

This code snippet demonstrates how to trigger fullscreen mode for a specific element (video-container) using a button. The script checks for API availability before attempting to enter fullscreen, ensuring broad compatibility with modern browsers. Using addEventListener keeps the markup clean and follows modern best practices.

Exiting Fullscreen Mode

To provide a comprehensive user experience, it’s also crucial to know how to exit fullscreen mode. Users or developers might want to offer an option to revert to the standard view after entering fullscreen mode. Here’s how you can implement this functionality:


<div id="exit-button">
    <button id="exit-btn">Exit Fullscreen</button>
</div>

<script>
document.getElementById("exit-btn").addEventListener("click", function() {
    if (document.exitFullscreen) {
        document.exitFullscreen();
    }
});
</script>

In this example, the exitFullScreen function enables the user to leave fullscreen mode by clicking an 'Exit Fullscreen' button. Note that document.exitFullscreen() exits the currently active fullscreen element, regardless of which element originally triggered the request.

Handling Fullscreen Changes with Events

The Fullscreen API provides events that notify you when an element enters or exits fullscreen mode. This is especially useful for toggling user interface elements or triggering other changes in your application:


document.addEventListener("fullscreenchange", function(event) {
    if (document.fullscreenElement) {
        console.log("Entered fullscreen mode");
    } else {
        console.log("Exited fullscreen mode");
    }
});

This event listener logs messages to the console based on whether the document is in fullscreen mode or not, helping developers understand the state transitions. Additionally, you should handle the fullscreenerror event to catch cases where the browser denies the request (e.g., due to security restrictions or user cancellation):

document.addEventListener("fullscreenerror", function(event) {
    console.error("Fullscreen request failed:", event.target.error);
});

Now, let's put it all together and see it all in an example:

A Full Example:


<div id="main-content">
    <button id="fs-btn">Go Fullscreen</button>
    <div id="video-container" style="position: relative; height: 100vh; display: flex; align-items: center; justify-content: center;">
        <div id="exit-button" style="display: none;">
            <button id="exit-btn">Exit Fullscreen</button>
        </div>
    </div>
</div>

<script>
const element = document.getElementById("video-container");
const exitBtn = document.getElementById("exit-btn");
const exitButtonContainer = document.getElementById("exit-button");

document.getElementById("fs-btn").addEventListener("click", function() {
    if (document.fullscreenEnabled) {
        element.requestFullscreen().catch(err => {
            console.error(`Error attempting to enable fullscreen: ${err.message}`);
        });
    }
});

exitBtn.addEventListener("click", function() {
    if (document.exitFullscreen) {
        document.exitFullscreen();
    }
});

function updateButtonVisibility() {
    exitButtonContainer.style.display = document.fullscreenElement ? "block" : "none";
}

document.addEventListener("fullscreenchange", updateButtonVisibility);
document.addEventListener("fullscreenerror", function(event) {
    console.error("Fullscreen request failed:", event.target.error);
});
</script>

Let's see the functionality of the code:

JavaScript Functions- goFullScreen(): This function makes the video container go into fullscreen mode. It first verifies that the browser supports the Fullscreen API via document.fullscreenEnabled, then calls the standard requestFullscreen() method.

  • exitFullScreen(): This function exits the fullscreen mode using the standard document.exitFullscreen() method.

Event Listeners for Fullscreen Changes- updateButtonVisibility(): This function adjusts the visibility of the exit button based on whether any element is currently in fullscreen mode.

  • The fullscreenchange event listener triggers this function whenever the fullscreen status changes, ensuring that the exit button only appears when the browser is in fullscreen mode and is hidden otherwise.

Compatibility and Browser Support

The JavaScript Fullscreen API is widely supported across modern browsers, including Chrome, Firefox, Safari, Opera, and Edge. Modern implementations use the standard methods without vendor prefixes. Historically, Safari required the -webkit- prefix (webkitRequestFullscreen, webkitExitFullscreen), but current versions fully support the unprefixed standard. For styling elements while in fullscreen mode, you can use the CSS :fullscreen pseudo-class:

:fullscreen {
    background-color: #000;
    color: #fff;
    padding: 20px;
}

Conclusion

The Fullscreen API in JavaScript is a powerful tool for enhancing user experience on the web. By providing interactive and immersive environments, developers can significantly improve engagement and satisfaction for users. The examples and methods discussed provide a foundation for incorporating fullscreen functionality into your web applications, ensuring a smooth and engaging user experience.

Practice

Practice

Which of the following statements are true regarding the JavaScript Fullscreen API?