0

I have a page that has multiple youtube videos. I want the video to play when someone clicks on the link that corresponds to each video.

For Example: When someone clicks on the video 2 link, video 2 plays.

HTML

   <!-- This loads the YouTube IFrame Player API code -->
<script src="http://www.youtube.com/player_api"></script>

<iframe id="ytplayer" type="text/html" width="640" height="390"
  src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1"
  frameborder="0"></iframe>
<a href="#" id="start">Video 1</a>

<br><hr>

<!-- This loads the YouTube IFrame Player API code -->
<script src="http://www.youtube.com/player_api"></script>

<iframe id="ytplayer2" type="text/html" width="640" height="390"
  src="http://www.youtube.com/embed/WdkT4_OJ2WU?enablejsapi=1"
  frameborder="0"></iframe>
<a href="#" id="start">Video 2</a>

JQUERY

    var ytplayer;

function onYouTubeIframeAPIReady() {
    ytplayer = new YT.Player('ytplayer', {

    });
}

$(document).ready(function () {
    $("#start").click(function () {
        ytplayer.playVideo();
    });
});

HERE IS MY JSFIDDLE Only clicking on video 1 works.

Display name
  • 177
  • 1
  • 3
  • 15

1 Answers1

1

Here is a demo that works as you expected.

I have removed the second script tag and modified the ids of the second iframe and a tags.

var ytplayer, ytplayer2;

function onYouTubeIframeAPIReady() {
    ytplayer = new YT.Player('ytplayer', {});
    ytplayer2 = new YT.Player('ytplayer2', {});
}

$(document).ready(function () {
    $("#start").click(function () {
        ytplayer.playVideo();
        return false;
    });
    $("#start2").click(function () {
        ytplayer2.playVideo();
        return false;
    });
});

The html part:

<!-- This loads the YouTube IFrame Player API code -->
<script src="http://www.youtube.com/player_api"></script>

<iframe id="ytplayer" type="text/html" width="640" height="390"
  src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1"
  frameborder="0"></iframe>
<a href="#" id="start">Video 1</a>

<br><hr>

<iframe id="ytplayer2" type="text/html" width="640" height="390"
  src="http://www.youtube.com/embed/WdkT4_OJ2WU?enablejsapi=1"
  frameborder="0"></iframe>
<a href="#" id="start2">Video 2</a>

Hope this helps.

ViRa
  • 714
  • 5
  • 7