DEV Community

Tom
Tom

Posted on

3 1

YouTube Player API for iframe embeds only works for muted content

This was a hard nut to crack:
I wanted to start a video playing when the parent container was scrolled into view. It appeared that this only works consistently for muted video's.

Example HTML:

<div class="video-container">
  <iframe
    id="player"
    width="560"
    height="315"
    src="https://www.youtube.com/embed/1XPdPKKRFaE?enablejsapi=1&mute=1"
    title="DCT introduction video"
    frameborder="0"
    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
    allowfullscreen
  ></iframe>
</div>
Enter fullscreen mode Exit fullscreen mode

So the crux is here: mute=1.

Accompanying JS:

let player;

// Will be automatically called when https://www.youtube.com/iframe_api is loaded
function onYouTubeIframeAPIReady() {
  player = new YT.Player("player", {
    events: {
      onReady: onPlayerReady,
    },
  });
}

function onPlayerReady(event) {
  // Start video play once in view
  let callback = (entries, observer) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        player.playVideo();
      } else {
        player.pauseVideo();
      }
    });
  };

  let observer = new IntersectionObserver(callback, {});
  let target = document.querySelector(".video-container");
  observer.observe(target);
Enter fullscreen mode Exit fullscreen mode

Notes:

  • "player" is the ID of the iframe used in the HTML
  • class "video-container" is the name of the element on which the intersection observer detects if the video container is visible in the viewport or not

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (1)

Collapse
 
robincingh profile image
Robin

Hi how can i add muted to src (if i dont have access to edit the code

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay