0
votes

I have a main YouTube video and some related videos at the bottom. YouTube video is loaded from a costum video name parameter in my url. If a video name exists YouTube iframe is loaded on page load but if a video name dosen't exists YT iframe isn't loaded until the user clicks a related video at the bottom. If the user clicks an related video the iframe is loaded and the same function onPlayerReady, and onPlayerStateChange should be used as the iframe was loaded from the begining. How can I insert the iframe in page and use the same function I use as it was loaded from the beginning. ? player.js

 var tag = document.createElement('script'),
     firstScriptTag = document.getElementsByTagName('script')[0],
     player;

    tag.src = "https://www.youtube.com/player_api";

    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

function onYouTubePlayerAPIReady() {
        player = new YT.Player('ytplayer', {
            height: height,
            width: width,
            videoId: yt_id,
            playerVars: {
            wmode: "transparent",
            controls: 0,
            showinfo: 0,
            rel: 0,
            modestbranding: 1,
            iv_load_policy: 3 //anottations
            },
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    };

function onPlayerReady(event) {
    //code here
    //I want to use this code even when the player is loaded after the         page is loaded (when the user clicks a related video at the bottom)
}

function onPlayerStateChange(event) {
    //here too
}

insert_frame.js

var tag = document.createElement('script'),
            firstScriptTag = document.getElementsByTagName('script')[0],
            player;

        tag.src = "https://www.youtube.com/player_api";

        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

        player = new YT.Player('ytplayer', {
            height: height,
            width: width,
            videoId: yt_id,
            playerVars: {
            wmode: "transparent",
            controls: 0,
            showinfo: 0,
            rel: 0,
            modestbranding: 1,
            iv_load_policy: 3 //anottations
            },
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
1

1 Answers

2
votes

How can I insert the iframe in page and use the same function I use as it was loaded from the beginning. ?

If i understand correctly, you want to do that because some videos ID on the url may be false and the player iframe will not play the video.

Well you don't need insert a frame just because a video ID exist when use click on a related videoo the bottom, use onError parameter from YouTube Player API.

This event fires if an error occurs in the player. The API will pass an event object to the event listener function. That object's data property will specify an integer that identifies the type of error that occurred. ...

If the videoID on the url doesn't exist an error will be send. Just hide the player for example and show it when the user click on a related video on the bottom.

With this solution you only need to load the player one and only one time without insert a frame into the code even if the id is wrong. A sample solution.

I made you a little example with a wrong videoID :

HTML

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div id="player"></div>
</body>
</html>

Javascript

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

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

// 3. This function creates an <iframe> (and YouTube player)
//    after the API code downloads.
var player;

function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
        height: '390',
        width: '640',
        videoId: 'l-gQLqv9f4',
        events: {
            'onError': onPlayerError,
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
        }
    });
}

// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
    $('#player').show();
    event.target.playVideo();
}

// 5. The API calls this function when the player's state changes.

function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING) {
    }
}

function stopVideo() {
    player.stopVideo();
}

function onPlayerError() {
  console.log("error on the video id. Iframe is hiding");
  $('#player').hide(); //or do what you want

}

Live demo: http://jsbin.com/mihikiqoma/1/edit?html,js,output