Need a script to play yt video and a progress bar with one button

Viewed 29

I need a button by which i can play youtube video and start progress bar also in one click.

In my site if i make a button with 'ID=BAR' then if i click the button the progress bar starts.

anything

Can anyone help me with this please. Thanks in advance.

1 Answers

You didn't specify how you would like to play your youtube video, but this would be one way of doing it, according to youtube iframe api documentation: https://developers.google.com/youtube/iframe_api_reference?hl=en

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="player"></div>
    <progress id="progressBar" value="0" max="100"></progress>
    <button id="btn">
      start video
    </button>
  </body>
</html>

const progress = document.getElementById("progressBar");
const button = document.getElementById("btn");
let interval;

function onPlayerStateChange(event) {
  if(event.data !== 1) {
    // video is stopped, stop updating progress
    clearInterval(interval);
    return;
  }

  interval = setInterval(function () {
    if (event.target.getPlayerState() === 1) {
     // video is playing, we are updating progress every second
     onProgress(event.target)
    }
  }, 1000);
}

function onProgress(p) {
  const playerTotalTime = p.getDuration();
  const playerCurrentTime = Math.round(p.getCurrentTime());
  const playerTimeDifference = (playerCurrentTime / playerTotalTime) * 100;
  const playerTimePercent = Math.round(playerTimeDifference);

  progress.value = playerTimePercent;
}

// Initialize iframe api script, check link with reference to youtube api iframe documentation for more info
const tag = document.createElement("script");
tag.src = "https://www.youtube.com/iframe_api";
document.head.appendChild(tag);

window.onYouTubeIframeAPIReady = () => {
  const player = new window.YT.Player("player", {
    height: "360",
    width: "640",
    videoId: "fJ9rUzIMcZQ",
    events: { onStateChange: onPlayerStateChange }
  });

  button.addEventListener("click", () => {
    player.playVideo();
  });
};

Here you can see working fiddle: https://jsfiddle.net/b2hs58gp/19/

Related