DEV Community

Tom
Tom

Posted on

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

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