Veet Thomson
Veet Thomson

Reputation: 67

How to set dynamic YouTube ID in an iframe

I am fetching YouTube video details based on ID using YouTube API. In the VIDEO details page I want to show the iframe and run the video on my specific page.

How can I change the ID in src?

src="https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1"

<iframe
      id="existing-iframe-example"
      width="640"
      height="360"
      src="https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1"
      frameborder="0"
      style="border: solid 4px #37474f"
    ></iframe>

    <script type="text/javascript">
      var tag = document.createElement("script");
      tag.id = "iframe-demo";
      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName("script")[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player("existing-iframe-example", {
          events: {
            onReady: onPlayerReady,
            onStateChange: onPlayerStateChange,
          },
        });
      }
      function onPlayerReady(event) {
        document.getElementById("existing-iframe-example").style.borderColor =
          "#FF6D00";
      }
      function changeBorderColor(playerStatus) {
        var color;
        if (playerStatus == -1) {
          color = "#37474F"; // unstarted = gray
        } else if (playerStatus == 0) {
          color = "#FFFF00"; // ended = yellow
        } else if (playerStatus == 1) {
          color = "#33691E"; // playing = green
        } else if (playerStatus == 2) {
          color = "#DD2C00"; // paused = red
        } else if (playerStatus == 3) {
          color = "#AA00FF"; // buffering = purple
        } else if (playerStatus == 5) {
          color = "#FF6DOO"; // video cued = orange
        }
        if (color) {
          document.getElementById("existing-iframe-example").style.borderColor =
            color;
        }
      }
      function onPlayerStateChange(event) {
        changeBorderColor(event.data);
      }
    </script>

Upvotes: 0

Views: 697

Answers (2)

stephenlcurtis
stephenlcurtis

Reputation: 190

You can do this by invoking the loadVideoById function on the player object.

Found in the official documentation here.

player.loadVideoById('M7lc1UVf-VE',0)

Upvotes: 0

Mohammad Ali Rony
Mohammad Ali Rony

Reputation: 4905

after getting the ID of the youtube video just change the src

let id ="w8LcxY43N5Y";

document.getElementById("existing-iframe-example").src = "https://www.youtube.com/embed/"+id;
<iframe
      id="existing-iframe-example"
      width="640"
      height="360"
      src="https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1"
      frameborder="0"
      style="border: solid 4px #37474f"
    ></iframe>

Upvotes: 2

Related Questions