Rick
Rick

Reputation: 2308

Youtube: Add two embeded videos in one page

This is more of a JavaScript question than YouTube API. I copied and modified a bit the YouTube iFrame API to add two videos at the same time. The first one plays automatically and the second does not.

The problem I am facing is that it is showing only the second video.

Here is what I have so far:

    <script>
    var tag = document.createElement('script');

    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    var player1;

    function onYouTubeIframeAPIReady() {
        player1 = new YT.Player('player1', {
            height: '315',
            width: '420',
            videoId: 'bHQqvYy5KYo',
            events: {
                'onReady': onPlayerReady
            }
        });
    }

    var player2;

    function onYouTubeIframeAPIReady() {
        player2 = new YT.Player('player2', {
            height: '315',
            width: '420',
            videoId: 'M3uWx-fhjUc',
            events: {
                'onReady': stopVideo
            }
        });
    }

    function onPlayerReady(event) {
        event.target.playVideo();
    }

    function stopVideo() {
        player.stopVideo();
    }
</script>


<div id="player1"></div>
<br>
<div id="player2"></div>

Fixed code after Answer:

    <script>
    var tag = document.createElement('script');

    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    var player1;
    var player2;

    function onYouTubeIframeAPIReady() {
        player1 = new YT.Player('player1', {
            height: '315',
            width: '420',
            videoId: 'bHQqvYy5KYo',
            events: {
                'onReady': onPlayerReady
            }
        });

        player2 = new YT.Player('player2', {
            height: '315',
            width: '420',
            videoId: 'M3uWx-fhjUc',
            events: {
                'onReady': stopVideo
            }
        });
    }


    function onPlayerReady(event) {
        event.target.playVideo();
    }

    function stopVideo() {
        player.stopVideo();
    }
</script>


<div id="player1"></div>
<br>
<div id="player2"></div>

Upvotes: 1

Views: 407

Answers (1)

Ikai Lan
Ikai Lan

Reputation: 2240

You have two functions named onYouTubeIframeAPIReady. Start by consolidating the code in a single function.

Upvotes: 1

Related Questions