Reputation: 180
There are multiple youtube videos playing in my site in a carousel. When a user click on a youtube video then I want to stop the auto scrolling of the carousel. Here is the code I am writing which is throwing me "players[player_id].getPlayerState() is not a function" error.
Also the youtube library is loading in my site from a thrid party javascript.
players = {};
window.onYouTubeIframeAPIReady = function(){
$('.youtube-video iframe').each(function() {
players[$(this).attr('id')] = new YT.Player($(this).attr('id'), {
events: {
'onStateChange': onPlayerStateChange($(this).attr('id'))
}
});
});
}
function onPlayerStateChange(player_id){
return function(event) {
if(players[player_id].getPlayerState() == 3 ||players[player_id].getPlayerState() == 1) {
//stop the auto scrolling
}
if(players[player_id].getPlayerState() == 0 || players[player_id].getPlayerState() == 2) {
//start auto scrolling.
}
}
}
Please let me know if you can find the issue in my code. Thanks in advance!
Upvotes: 1
Views: 6022
Reputation: 7251
You forgot some sample paramters like videoId: $(this).attr('id')
and events
was not placed at the good place.
I post you the correct code :
HTML
<div class="youtube-video" id="O1RHkPGb31Q"></div>
<div class="youtube-video" id="VjRb3RjqncQ"></div>
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);
players = {};
window.onYouTubeIframeAPIReady = function(){
$('.youtube-video').each(
function() {
players[$(this).attr('id')] = new YT.Player($(this).attr('id'),
{
videoId: $(this).attr('id'),
events: { 'onStateChange': onPlayerStateChange($(this).attr('id')) }
});
});
};
function onPlayerStateChange(player_id){
return function(event) {
if(players[player_id].getPlayerState() == 3 || players[player_id].getPlayerState() == 1) {
//stop the auto scrolling
console.log("stop scolling video" + player_id);
}
if(players[player_id].getPlayerState() == 0 || players[player_id].getPlayerState() == 2) {
//start auto scrolling.
console.log("start scolling video" + player_id);
}
};
}
Live demo : http://jsbin.com/nisetafoga/1/edit?html,js,console,output
Upvotes: 2