I'm working on a webpage. I'm using jQuery load (AJAX) function to dynamically load new content (articles) into the content div. In this div, multiple videos gets loaded. What I want is to play only one youtube video at a time. If one video is in playing state, and the user clicks on another video, the previous one should get paused. I have used onYouTubeIframeAPIReady() script code for the functionality. The code is working only for the videos that are loaded on first instance. As I scroll down the page, different videos are loaded on page (through AJAX call) and the code doesnot work on new content. Also shows error like:
TypeError: this.pauseVideo is not a function-- this.pauseVideo();
I have added the script code below:
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
var num = firstScriptTag.length;
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubeIframeAPIReady() {
var $ = jQuery;
var players = [];
$("iframe").filter(function(){
return this.src.indexOf('https://www.youtube.com/') == 0}).each( function (k, v) {
var $urls_get=$(this).attr("src");
var $new_url=$urls_get+"&enablejsapi=1";
if (!this.id) {
this.id='embeddedvideoiframe' + k;
this.src=$new_url;
}
players.push(new YT.Player(this.id, {
events: {
'onStateChange': function(event) {
if (event.data == YT.PlayerState.PLAYING) {
$.each(players, function(k, v) {
if ('embeddedvideoiframe' + k != event.target.getIframe().id) {
this.pauseVideo();
}
});
}
}
}
}))
});
}
Please help. Thanks in advance.