EthicsComputerCourses
Join training +91 90532 10052

Fullscreen API

HTML · Lesson 147 of 234 Advanced 10 min read Updated

By the end of this lesson you will be able to put any element on the whole screen, such as a photo, a video player or a slide, style it while it is fullscreen, react when the user leaves, and give phones without the API a working fallback.

What you should know first: HTML Web APIs for feature detection and permissions, Video Integration for the <video> element, Secure Iframes & Sandbox Attributes for the allow attribute, and Keyboard Navigation & Focus Management.

Two kinds of fullscreen

Press F11 in a desktop browser and the whole browser window fills the screen. That is browser fullscreen. The page is not told anything special, and it still shows everything it showed before.

The Fullscreen API is different. Your JavaScript picks one element, and the browser shows only that element across the whole screen. Everything else on the page is hidden behind it. Think of a cricket stadium: the match goes on everywhere, but for a replay the big screen shows one moment, very large, for everyone. The Fullscreen API puts one element on that big screen.

Because they are different, F11 does not set document.fullscreenElement and does not match the :fullscreen selector. Only the API does.

The whole API on one page

MemberBelongs toWhat it does
element.requestFullscreen()Any elementAsks to show this element fullscreen. Returns a promise.
document.exitFullscreen()DocumentLeaves fullscreen. Returns a promise.
document.fullscreenElementDocumentThe element now fullscreen, or null
document.fullscreenEnabledDocumenttrue if this page is allowed to use fullscreen at all
fullscreenchange eventElement, bubbles to documentFires on entering and on leaving
fullscreenerror eventElement, bubbles to documentFires when a request is refused
:fullscreenCSS pseudo-classMatches the element while it is fullscreen
::backdropCSS pseudo-elementThe layer drawn behind the fullscreen element

These unprefixed names work in Chrome and Edge 71+, Firefox 64+ and Safari 16.4+ on Mac and iPad. On iPhone, Safari does not offer element fullscreen at all. Only a <video> can go fullscreen there, through Apple's own player. Every fullscreen feature therefore needs a fallback.

The rules the browser enforces

A page that could take over the screen whenever it liked could fake a bank's login screen or trap the user. So the browser checks several things before it says yes.

  1. User activation. The request must come from a real user action, such as a click, a tap or a key press. This is called transient activation: it lasts a few seconds after the action (about five in Chrome). A request on page load, from a timer, or after a slow await fetch() is refused.
  2. Permission in frames. A page inside an <iframe> from another site may use fullscreen only if the parent allows it with allow="fullscreen". The older attribute allowfullscreen does the same job and you will see it in YouTube embed codes. A Permissions-Policy: fullscreen=() response header can switch it off for a whole site.
  3. Esc always wins. Pressing Esc, or the system's exit gesture, always ends fullscreen. Your page cannot cancel it. Listen for fullscreenchange to notice.
  4. The element must be in the page. If you remove the fullscreen element from the DOM, the browser leaves fullscreen.

When a request fails, the promise rejects with a TypeError and fullscreenerror fires. Always add a catch.

JavaScript
async function showFullscreen(element) {
  if (!document.fullscreenEnabled) return false;   // blocked here (iframe policy, iPhone...)
  try {
    await element.requestFullscreen();
    return true;
  } catch (error) {
    console.log(`Fullscreen refused: ${error.name}`);
    return false;
  }
}

Styling with :fullscreen and ::backdrop

When an element goes fullscreen, the browser's own stylesheet stretches it to fill the screen and puts it in the top layer, the same layer a modal <dialog> uses. Behind it sits a ::backdrop, which is black by default. You can style both:

CSS
.viewer:fullscreen {
  background: #111;
  color: white;
  padding: 24px;
}
.viewer::backdrop {
  background: #111;
}

A common surprise: an image that looked fine in the page now touches the edges, or a light card sits on a black backdrop. Write :fullscreen rules for the layout you want on a big screen, such as larger text and a darker background.

Ananya wants a gallery for her class trip photos. Each photo should be viewable fullscreen, with Previous and Next buttons and arrow keys.

Step 1: put the photo and its controls inside one <figure>. We make the figure fullscreen, not the <img>, so the buttons and caption come along.

Step 2: the toggle button checks document.fullscreenElement. If something is fullscreen, it exits; otherwise it requests fullscreen.

Step 3: if the API is not allowed or the request is refused, add a fake-fullscreen class instead. It uses position: fixed to cover the page. This is the fallback an iPhone needs.

Step 4: fullscreenchange updates the button text, because the user may leave with Esc instead of the button.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Class trip gallery</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    .viewer { margin: 0; background: #f4f1ea; padding: 12px; border-radius: 8px; }
    .viewer img { display: block; width: 100%; height: 260px; object-fit: contain; }
    .bar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-top: 8px; }
    #caption { flex: 1; }
    .viewer:fullscreen, .viewer.fake-fullscreen {
      display: grid; grid-template-rows: 1fr auto; background: #111; color: white; border-radius: 0;
    }
    .viewer.fake-fullscreen { position: fixed; inset: 0; z-index: 10; }
    .viewer:fullscreen img, .viewer.fake-fullscreen img { height: 100%; min-height: 0; }
    .viewer::backdrop { background: #111; }
  </style>
</head>
<body>
  <h1>Class trip album</h1>
  <figure class="viewer" id="viewer">
    <img id="photo" src="https://course.ethicscomputer.in/assets/samples/landscape.svg" alt="">
    <figcaption class="bar">
      <button type="button" id="prev">Previous</button>
      <button type="button" id="next">Next</button>
      <span id="caption"></span>
      <button type="button" id="toggle">View fullscreen</button>
    </figcaption>
  </figure>
  <p id="note" role="status"></p>

  <script>
    const photos = [
      { src: "https://course.ethicscomputer.in/assets/samples/landscape.svg", alt: "Hills and a river at sunrise", caption: "Sunrise on the hills" },
      { src: "https://course.ethicscomputer.in/assets/samples/portrait.svg", alt: "A tall clock tower under a blue sky", caption: "The clock tower, Lucknow" },
      { src: "https://course.ethicscomputer.in/assets/samples/logo.svg", alt: "Chai Corner tea stall sign", caption: "Our favourite tea stall" }
    ];
    const viewer = document.querySelector("#viewer");
    const toggle = document.querySelector("#toggle");
    const note = document.querySelector("#note");
    let index = 0;

    function show(i) {
      index = (i + photos.length) % photos.length;
      const p = photos[index];
      document.querySelector("#photo").src = p.src;
      document.querySelector("#photo").alt = p.alt;
      document.querySelector("#caption").textContent = `${index + 1} of ${photos.length}: ${p.caption}`;
    }

    function isFull() {
      return document.fullscreenElement === viewer || viewer.classList.contains("fake-fullscreen");
    }

    function updateButton() {
      toggle.textContent = isFull() ? "Exit fullscreen" : "View fullscreen";
    }

    async function enter() {
      if (document.fullscreenEnabled && viewer.requestFullscreen) {
        try {
          await viewer.requestFullscreen();
          note.textContent = "Real fullscreen. Press Esc to leave.";
          return;
        } catch (error) {
          note.textContent = `Fullscreen was refused (${error.name}), so the page fills the window instead.`;
        }
      } else {
        note.textContent = "Fullscreen is not available here, so the page fills the window instead.";
      }
      viewer.classList.add("fake-fullscreen");
      updateButton();
    }

    function leave() {
      if (document.fullscreenElement) document.exitFullscreen();
      viewer.classList.remove("fake-fullscreen");
      updateButton();
    }

    toggle.addEventListener("click", () => (isFull() ? leave() : enter()));
    document.querySelector("#prev").addEventListener("click", () => show(index - 1));
    document.querySelector("#next").addEventListener("click", () => show(index + 1));
    document.addEventListener("fullscreenchange", updateButton);

    document.addEventListener("keydown", (event) => {
      if (event.key === "ArrowRight") show(index + 1);
      if (event.key === "ArrowLeft") show(index - 1);
      if (event.key === "Escape" && viewer.classList.contains("fake-fullscreen")) leave();
    });

    show(0);
  </script>
</body>
</html>

Click "View fullscreen". In Chrome and Edge the editor's frame is allowed to go fullscreen, so the figure fills the screen with a dark background and the button says "Exit fullscreen". Press the arrow keys to move between photos, then press Esc: the button text changes back, thanks to fullscreenchange. If your browser refuses, you see the message and the fixed overlay instead, and Esc closes it through our own keydown code.

Watching the events and the activation rule

The next example is a projector timer for a classroom in Pune. It logs every event and has a second button that waits six seconds before asking. By then the click's activation has expired, so the request is refused.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Projector timer</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    #timer { font-size: 2rem; text-align: center; padding: 16px; background: #e8f0fe; border-radius: 8px; }
    #timer:fullscreen { font-size: 12vw; display: grid; place-items: center; background: #0b3d91; color: white; }
    #timer::backdrop { background: #0b3d91; }
    #log { background: #f5f5f5; padding: 8px; min-height: 5em; }
  </style>
</head>
<body>
  <div id="timer">10:00</div>
  <p>
    <button type="button" id="now">Fullscreen now</button>
    <button type="button" id="late">Fullscreen in 6 seconds</button>
  </p>
  <pre id="log"></pre>

  <script>
    const timer = document.querySelector("#timer");
    const log = (text) => (document.querySelector("#log").textContent += text + "\n");
    log(`fullscreenEnabled: ${document.fullscreenEnabled}`);

    async function ask() {
      log(`user activation active: ${navigator.userActivation.isActive}`);
      try {
        await timer.requestFullscreen();
      } catch (error) {
        log(`refused: ${error.name}`);
      }
    }

    document.querySelector("#now").addEventListener("click", ask);
    document.querySelector("#late").addEventListener("click", () => {
      log("waiting 6 seconds...");
      setTimeout(ask, 6000);
    });
    document.addEventListener("fullscreenchange", () => {
      log(`fullscreenchange: ${document.fullscreenElement ? "entered #" + document.fullscreenElement.id : "left"}`);
    });
    document.addEventListener("fullscreenerror", () => log("fullscreenerror event"));
  </script>
</body>
</html>

"Fullscreen now" logs user activation active: true, and then fullscreenchange: entered #timer where fullscreen is allowed. Press Esc to see fullscreenchange: left. "Fullscreen in 6 seconds" logs user activation active: false, then refused: TypeError and fullscreenerror event. navigator.userActivation is a small helper that tells you whether the page has an unexpired user action.

A fullscreen video player

The real-world use is a video player with your own controls. Make the wrapper fullscreen, not the <video>. A fullscreen <video> shows the browser's controls and hides yours, including your captions menu and your "next lecture" button.

HTML
<div class="player" id="player">
  <video id="lecture" src="lecture-12.mp4" playsinline></video>
  <div class="controls">
    <button type="button" id="play">Play</button>
    <button type="button" id="full">Fullscreen</button>
  </div>
</div>

<script>
  const player = document.querySelector("#player");
  const video = document.querySelector("#lecture");

  document.querySelector("#full").addEventListener("click", async () => {
    if (document.fullscreenElement) {
      await document.exitFullscreen();
    } else if (document.fullscreenEnabled) {
      await player.requestFullscreen().catch(() => {});
    } else if (video.webkitEnterFullscreen) {
      video.webkitEnterFullscreen();   // iPhone: Apple's own video player takes over
    }
  });
</script>

On a laptop the whole player, with your buttons, fills the screen. On an iPhone the last branch runs, and the video plays in Apple's fullscreen player with Apple's controls. That is the best an iPhone allows today.

Common mistakes

  • Requesting fullscreen on page load or after a slow await. The user activation has expired. Call it directly inside the click handler.
  • No catch on the promise. A refusal becomes an "Uncaught (in promise)" error and the user sees nothing.
  • Tracking state with your own variable. Esc changes the state without your button. Read document.fullscreenElement in fullscreenchange.
  • Fullscreening the <video> instead of its wrapper. Your custom controls disappear.
  • Forgetting allow="fullscreen" on an embed. The player's fullscreen button does nothing.
  • No iPhone fallback. Detect support and offer an overlay or the video's own fullscreen.

Interview questions

1. Why does requestFullscreen() fail when called as soon as the page loads?

Browsers require transient user activation, meaning a recent click, tap or key press. On page load there is none, so the promise rejects with a TypeError and fullscreenerror fires. This stops pages from taking over the screen without the user's choice.

2. What is the difference between pressing F11 and using the Fullscreen API?

F11 makes the browser window fill the screen but the page stays the same, and document.fullscreenElement remains null. The API shows one chosen element in the top layer, hides the rest of the page, and makes :fullscreen match that element.

3. How do you let an embedded video player go fullscreen?

Add allow="fullscreen" to the <iframe>, or the older allowfullscreen attribute. Cross-origin frames are blocked without it. A Permissions-Policy header on the parent page can still switch the feature off.

4. How does your code know the user pressed Esc to leave fullscreen?

Listen for fullscreenchange on the document and check whether document.fullscreenElement is null. You cannot block Esc, so all your fullscreen state should be derived from this event.

5. Why fullscreen a wrapper element rather than the <video> itself?

A fullscreen video shows only the browser's built-in controls. Making the wrapper fullscreen keeps your own buttons, captions and overlays visible, and you style them with :fullscreen.

Key points

  • element.requestFullscreen() and document.exitFullscreen() return promises; always handle rejection.
  • Requests need transient user activation, so call them directly inside a click or key handler.
  • document.fullscreenElement and the fullscreenchange event are the truth; Esc always exits.
  • Style the fullscreen element with :fullscreen and the layer behind it with ::backdrop.
  • Iframes need allow="fullscreen" (or allowfullscreen) for cross-origin content.
  • iPhone Safari has no element fullscreen: give an overlay fallback or video.webkitEnterFullscreen().

Exercise

Build a three-slide presentation for a Class 9 maths lesson on fractions. Put the slides in one <section> with a "Present" button. In fullscreen the slide text should be at least three times larger and centred, with a dark ::backdrop. Arrow keys move between slides, a counter shows "Slide 2 of 3", and the button text changes between "Present" and "Stop presenting" even when the user presses Esc. If fullscreen is refused, use a fixed overlay instead.

Show solution
HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Fractions</title>
  <style>
    #deck { border: 1px solid #ccc; padding: 16px; }
    #deck:fullscreen, #deck.fake { display: grid; place-content: center; text-align: center; font-size: 3rem; background: #1b2a49; color: white; }
    #deck.fake { position: fixed; inset: 0; }
    #deck::backdrop { background: #1b2a49; }
  </style>
</head>
<body>
  <section id="deck">
    <p id="slide" aria-live="polite"></p>
    <p id="count"></p>
    <button type="button" id="present">Present</button>
  </section>
  <script>
    const slides = ["A fraction is a part of a whole", "1/2 of 8 laddoos is 4 laddoos", "3/4 means 3 parts out of 4 equal parts"];
    const deck = document.querySelector("#deck");
    const button = document.querySelector("#present");
    let n = 0;
    const show = () => {
      document.querySelector("#slide").textContent = slides[n];
      document.querySelector("#count").textContent = `Slide ${n + 1} of ${slides.length}`;
    };
    const presenting = () => document.fullscreenElement === deck || deck.classList.contains("fake");
    const label = () => (button.textContent = presenting() ? "Stop presenting" : "Present");

    button.addEventListener("click", async () => {
      if (presenting()) {
        if (document.fullscreenElement) await document.exitFullscreen();
        deck.classList.remove("fake");
      } else {
        try { await deck.requestFullscreen(); }
        catch { deck.classList.add("fake"); }
      }
      label();
    });
    document.addEventListener("fullscreenchange", label);
    document.addEventListener("keydown", (e) => {
      if (e.key === "ArrowRight") n = Math.min(n + 1, slides.length - 1);
      if (e.key === "ArrowLeft") n = Math.max(n - 1, 0);
      if (e.key === "Escape") { deck.classList.remove("fake"); label(); }
      show();
    });
    show();
  </script>
</body>
</html>

The catch covers both a missing permission and an iPhone, where requestFullscreen does not exist and calling it throws. The fullscreenchange listener keeps the label right when Esc ends real fullscreen.

Quick Quiz

1. What does document.fullscreenElement hold after the user presses Esc to leave fullscreen?

2. A button calls requestFullscreen() inside setTimeout(..., 10000). What happens?

3. Which CSS styles the layer drawn behind a fullscreen element?

4. What does an embedded YouTube <iframe> need for its fullscreen button to work?

Learn HTML with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call