The Bumpaster
The Bumpaster

Reputation: 964

Dynamic youtube iframe in javascript and jQuery

I'm going crazy, trying to fix this and it wont work the way I want it to work,ahhh I feel like a child :/

var videoID;

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

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

videoID = sessionStorage.getItem("key");

var onYouTubeIframeAPIReady = function(){
    player = new YT.Player('player', {
        height: '315',
        width: '560',
        videoId: videoID,
        events: {
            'onReady': onPlayerReady
        }
    });
}

//The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
    console.log(videoID);
}

function searchQuery() {
    //Declare selectors
    var queryContainer = $('div.search-box ul');
    var searchBox = $('div#search-bar input[type=search]');
    
    //Declare variables from input elements :)
    var search = $(searchBox).val();
    var checker = search.length;
    
    //Check if the input is empty string
    if(search!=''){
        //Declare the YoutubeAPI link with youtube APIkey
        var theAPI = "https://www.googleapis.com/youtube/v3/search?part=snippet&q="+search+"&maxResults=15&key=AIzaSyA9ej5NSrEqzex76U_xE3PPJlb2rELrW9M";

        //Get JSON string from YoutubeAPI link
        $.getJSON(theAPI, function(data){

            //Append 5 titles to the div
            for(var i=0; i<=5; ++i){
                
                //Using the kind property from YoutubeAPI determine is it a profile or video
                if(data.items[i].id.kind === 'youtube#video'){
                    $(queryContainer).append('<li><p><a href="#" data-id="' +data.items[i].id.videoId+'">' +data.items[i].snippet.title+'</a></p></li>');
                }else if(data.items[i].id.kind === 'youtube#channel'){
                    $(queryContainer).append('<li><p><a href="https://www.youtube.com/user/'+data.items[i].snippet.title+'">' +data.items[i].snippet.title+'</a></p></li>')
                }
            }
            $('div.search-box a').on('click', function(){
                
                $('div#player-box').empty();
                $('div#player-box').append('<div id="player"></div>');
                sessionStorage.setItem('key', $(this).data("id"));
                
                onYouTubeIframeAPIReady();
                
            });
        });

        //Check if the input value is changing, if it does cleares the previous output
        if(checker){
            $(queryContainer).empty();
        }
        
    }else{
        $(queryContainer).empty();
        return false;
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="player"></div>

here is a question:

function onYouTubeIframeAPIReady(){
    player = new YT.Player('player', {
        height: '315',
        width: '560',
        videoId: videoID,
        events: {
            'onReady': onPlayerReady
        }
    });
}

How to delete this player object and create a new one on a click event? I really want this working, please someone help :)

Upvotes: 3

Views: 2373

Answers (1)

jlmcdonald
jlmcdonald

Reputation: 13667

Is there a specific reason you want to destroy the player object and recreate it? If your goal is to just load a new video, you could always do this:

        $('div.search-box a').on('click', function(){                
            player.loadVideo($(this).data("id"));
            sessionStorage.setItem('key', $(this).data("id"));
        });

(you might need to declare the player variable in such a way that your click handler could access its scope, whether that be as a global, etc.)

However, if you really need to destroy the player itself and recreate it, I wonder if the problem lies in the fact that, on your click, you aren't changing the value of the 'videoID' variable (which the onYouTubePlayerAPIReady function needs to instantiate the new player); rather, you only change the value of the sessionStorage key.

Upvotes: 2

Related Questions