I'm using the iframe API to generate a youtube video embedded on my website.
loadAPIPls('WQBUy6t3f0U');
function loadAPIPls(idYTB) {
loadYouTubeAPI();
window.onYouTubeIframeAPIReady = function() {
createYouTubePlayer(idYTB);
}
}
function loadYouTubeAPI() {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
function createYouTubePlayer(id) {
player = new YT.Player('player', {
height: '360',
width: '640',
videoId: id,
events: {
'onReady': onPlayerReady,
}
});
}
<div id="player"></div>
The video is displayed without any problem. The issue arises when I recall the function with another ID without refreshing the page.
button on click loadAPIPls('DOWDNBu9DkU')
for example.
And the video is not updating, it's the same. I would like the player to update with the new video.
I found by myself
function loadAPIPls(IdYtb) {
if (typeof YT === 'undefined' || typeof YT.Player === 'undefined') {
loadYouTubeAPI();
window.onYouTubeIframeAPIReady = function () {
createYouTubePlayer(IdYtb);
}
} else {
createYouTubePlayer(IdYtb);
}
}
function createYouTubePlayer(id) {
var iframePlayer = document.querySelector("iframe#player");
if (iframePlayer == null) {
// create the YT.Player object if it doesn't exist
player = new YT.Player('player', {
height: '360',
width: '640',
videoId: id,
events: {
'onReady': onPlayerReady,
}
});
} else {
load1(id);
}
}
function load1(id) {
player.loadVideoById(id);
}