allowfullscreen
an HTML attribute for the iframe tag

How to check if an element is in fullscreen mode?

Answers:

  • To check if an element is in fullscreen mode in a web page, you can use the Fullscreen API provided by the browser. Specifically, you can check if a particular element is currently in fullscreen mode by accessing the document.fullscreenElement property.

    Here's a simple way to check if a specific element is in fullscreen mode:

    1. Using document.fullscreenElement: This property returns the element that is currently in fullscreen mode, or null if no elements are in fullscreen.

    2. Using Element.requestFullscreen() and document.exitFullscreen(): You can toggle fullscreen mode on the element.

    Here is a code example:

    // Assume you have an element with the ID 'myElement'
    const myElement = document.getElementById('myElement');
    
    // Function to check if the element is in fullscreen mode
    function isElementInFullscreen(element) {
        return document.fullscreenElement === element;
    }
    
    // Example usage
    if (isElementInFullscreen(myElement)) {
        console.log('The element is in fullscreen mode.');
    } else {
        console.log('The element is NOT in fullscreen mode.');
    }
    
    // Optional: Toggle fullscreen
    function toggleFullscreen(element) {
        if (!isElementInFullscreen(element)) {
            // Request fullscreen for the element
            element.requestFullscreen().catch(err => {
                console.error(`Error attempting to enable fullscreen mode: ${err.message}`);
            });
        } else {
            // Exit fullscreen mode
            document.exitFullscreen();
        }
    }
    

    Key Points:

    • Use document.fullscreenElement to check if a specific element is currently in fullscreen mode.
    • You can toggle fullscreen by calling requestFullscreen() on the element and exitFullscreen() on the document.

    Notes:

    • Ensure that your code is executed in an environment where the Fullscreen API is supported (most modern browsers).
    • Remember that fullscreen actions usually require a user gesture, such as a click.

Related Questions: