I'm building a website witch contains a 15 youtube embeds on 1 page, and I have a youtube-api javascript code witch plays them continuously, and changes a class that surrounds the embed. The problem is that the code occasionally doesn't fire, and this only happens online, not on my computer. I think this is because it sometimes takes too mutch time to load the 15 embeds with a slow connection, maybe the code fires when the players aren't ready, or too late? well... I dont know. I tried wrapping the whole code in a SetTimout() thing, but no luck. Anybody have a solution? Help will be greatly appreciated!
CODE (PARTIALLY):
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player1;var player2;
function onYouTubeIframeAPIReady() {
player1 = new YT.Player('player1', {
events: {
'onStateChange': onPlayerStateChange1
}
});
player2 = new YT.Player('player2', {
events: {
'onStateChange': onPlayerStateChange2
}
});
---- etc... (untill player 15)
function onPlayerStateChange1(event) {
if (event.data == 0) {
player2.playVideo();
};
if (event.data == 1) {
document.getElementById("redlow1").setAttribute("class", "hero-unit77");
document.getElementById("redhigh1").setAttribute("class", "hero-unit88");
};
if (event.data == 2 || event.data == 0 || event.data == 5) {
document.getElementById("redlow1").setAttribute("class", "hero-unit7");
document.getElementById("redhigh1").setAttribute("class", "hero-unit8");
};
}
function onPlayerStateChange2(event) {
if (event.data == 0) {
player3.playVideo();
};
if (event.data == 1) {
document.getElementById("redlow2").setAttribute("class", "hero-unit77");
document.getElementById("redhigh2").setAttribute("class", "hero-unit88");
};
if (event.data == 2 || event.data == 0 || event.data == 5) {
document.getElementById("redlow2").setAttribute("class", "hero-unit7");
document.getElementById("redhigh2").setAttribute("class", "hero-unit8");
};
}
---- etc... (untill player 15)
One thing that may help you is to not use a different state change event listener for each player object. Instead, use a single listener for all of your players, as any state change event will also include a reference to the player that raised the event (in the 'target' attribute of the event object). First, in the 'events' parameter of each player creation function, bind the 'onReady' to a function that will load a reference to that player into a global object, and bind the 'onStateChange' all to the same function. Something like this (note: untested code written very late at night ... if you get errors you can't figure out, we'll work through them!):
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player1, player2;
var players={};
function onYouTubeIframeAPIReady() {
player1 = new YT.Player('player1', {
events: {
'onReady': function() {
players.['player1']=player1;
}
'onStateChange': onPlayerStateChange
}
});
player2 = new YT.Player('player2', {
events: {
'onReady': function() {
players['player2']=player2;
}
'onStateChange': onPlayerStateChange;
}
});
---- etc... (untill player 15)
Then, you can define the state change listener function, and use the event.target for reference:
onPlayerStateChange = function(event) {
if (event.data == 0) {
players[event.target.a.id].playVideo();
};
if (event.data == 1) {
document.getElementById(event.target.a.id.replace("player","redlow")).setAttribute("class", "hero-unit77");
document.getElementById(event.target.a.id.replace("player","redhigh")).setAttribute("class", "hero-unit88");
};
if (event.data == 2 || event.data == 0 || event.data == 5) {
document.getElementById(event.target.a.id.replace("player","redlow")).setAttribute("class", "hero-unit7");
document.getElementById(event.target.a.id.replace("player","redhigh")).setAttribute("class", "hero-unit8");
};
};
Got it to work finnaly, the solution was using the onload function of the Yutube iframe like so:
<iframe onload="floaded1()" id="player1">
with this script:
function floaded1() {
player1 = new YT.Player('player1', {
events: {
'onStateChange': function (event) {
if (event.data == 0) {
player2.playVideo();
};
if (event.data == 1) {
document.getElementById("redlow1").setAttribute("class", "hero-unit77");
document.getElementById("redhigh1").setAttribute("class", "hero-unit88");
};
if (event.data == 2 || event.data == 0 || event.data == 5) {
document.getElementById("redlow1").setAttribute("class", "hero-unit7");
document.getElementById("redhigh1").setAttribute("class", "hero-unit8");
};
}
}
});
}
Related
I am trying to create a button that allows the user to click it and stop the embedded youtube video. However, whenever I try and call the player object itself to use the function player.playVideo() I get an error saying the function is not defined.
Player is globally defined and set when the Youtube API loads (just like the tutorial on their website). Function calls to playVideo work just fine when events trigger their usage, but using it outside of those simply do not work.
'''javascript
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
isReady=true;
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
playVideo();
}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.pauseVideo();
}
function playVideo() {
player.playVideo();
}
//The function that is run when the button is pressed, only in this case
// stopVideo not work!
function togglePlay() {
if(isPlaying) {
stopVideo();
} else {
playVideo();
}
}
'''
Expected: Youtube video plays
Actual: Error player.playVideo is not a function
I solved the issue. Something weird happens with even setting up buttons with onclick functions that use the player before the player is finished loading. To solve this, I moved all button declarations and functions inside the onPlayerReady(event) function and used event.target.play or event.target.pause and that worked perfectly. My advice is just to contain any declarations of buttons that use the youtube player functions inside of the onPlayerReady.
When $('#myModal').on('show.bs.modal' gets called. I get this:
TypeError: player.loadVideoById is not a function. (In 'player.loadVideoById(x)', 'player.loadVideoById' is undefined)
https://jsfiddle.net/rdbj3ty1/5/
In JS Fiddle the code works, but when I add it to my code base, it stops working. I have a lot of other js code and CSS code that it must be interfering with. Is there a way to prevent the interference? Maybe wrap my js code with a block or add more specific references? Is namespacing the issue? If so, how do I do that?
I don't really know what to try. I have spent 2 days on this and getting nowhere.
JS
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'novideoid',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
$('.open-popup').click(function() {
event.target.playVideo();
});
$('.close-popup').click(function(e) {
player.stopVideo();
});
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if(event.data === 0) {
$('.close.close-popup').click();
}
}
function stopVideo() {
player.stopVideo();
}
$(function () {
onYouTubeIframeAPIReady();
$('#myModal').on('show.bs.modal', function(e) {
var videoId = $(e.relatedTarget).data('video-id');
var x = new String(videoId);
player.loadVideoById(x);
});
});
I want to play another video, which I will get from my database, but I try it with some sample, which is not working at all, here is my sample code:
<script>
// create youtube player
var player;
function onYouTubePlayerAPIReady(id) {
if (id == null) {var t = '0Bmhjf0rKe8';}
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: t,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
// Here I want to call function again, function executes, but video will not played
onYouTubePlayerAPIReady('yeDkcSZta2Y');
}
}
There you can see, when video ends I call onYouTubePlayerAPIReady() with new video ID, it executes as well, but video do not play. I think it will be because the onPlayerReady() do not executes, or something.
How to fix this, or what change to work it properly?
Here is an example that works. Call queueVideo() to load a string containing comma separated video ids of all the videos that you want to play or just one video. When there are no video left in the queue, this plays the default video '0Bmhjf0rKe8'. I never use onPlayerReady(). In fact, if I remember correctly, it was never called so I implemented using the technique shown below.
<script type="text/javascript">
// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
//
// Replaces the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
var videosQueuedCount;
function onYouTubePlayerAPIReady() {
videosQueuedCount = 1;
var vars = {
autoplay: 1,
enablejsapi: 1,
controls: 1
}
player = new YT.Player('ytplayer', {
height: '390',
width: '640',
playerVars: vars,
videoId:'0Bmhjf0rKe8',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(evt) {
}
function playVideo(VID) {
window.top.scrollTo(0,410);
videosQueuedCount = 1;
player.loadVideoById(VID);
}
function queueVideo(queuedCount,VID) {
window.top.scrollTo(0,410);
videosQueuedCount = queuedCount;
player.loadPlaylist(VID);
player.playVideo();
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
videosQueuedCount -= 1;
if (videosQueuedCount < 1) {
videosQueuedCount = 1;
playVideo('0Bmhjf0rKe8');
}
}
}
</script>
<div class="video-container"><div id="ytplayer"></div></div>
I'm using the YouTube API in conjunction with Cyclone Slider. The goal is to pause the slideshow once the YouTube starts playing. I'm using the following code which works nicely:
<script>
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
</script>
<script>
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('video', {
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
if(event.data === 1) {
$(".cycle-slideshow").cycle('pause');
}
if(event.data === 2) {
$(".cycle-slideshow").cycle('resume');
}
}
</script>
However, it only seems to work if I do a refresh of the page. If I navigate between pages and return to the homepage, it will no longer work.
Any suggestions for why this is the case? I've tried a few suggestions I found on Google but couldn't get any to work. I'm a little lost on this one.
Any help would be greatly appreciated.
Try the following code, it works for me -
function loadYouTube(targetId){
ytplayer = new YT.Player(targetId, {
events: {
'onStateChange': function(event){
/** YouTube API
-1 (unstarted)
0 (ended)
1 (playing)
2 (paused)
3 (buffering)
5 (video cued)
**/
if (event.data == 1) {
//do your work here
}
console.log(event.data)
}
}
});
}
Is it possible to detect the finish of a youtube buffering through javascript? Here http://code.google.com/intl/de-DE/apis/youtube/js_api_reference.html are a lot of methods but no one has an event that says "finished with buffering".
var ytplayer;
function onYouTubePlayerReady(playerId) {
ytplayer = document.getElementById("myytplayer");
checkBuffer();
}
function checkBuffer(){
if(ytplayer.getVideoBytesLoaded() == ytplayer.getVideoBytesTotal()){
alert('Buffer Complete!');
}else{
var t = setTimeout(function(){
Editor.split();
},1000);
}
}
I know this question is old but the answer may still be helpful to some:
The YouTube video can be in one of 6 states:
-1 – unstarted
0 – ended
1 – playing
2 – paused
3 – buffering
5 – video cued
When this state changes (i.e. when the video stops buffering and enters a 'paused' or a 'played' state), the "onStateChange" event is triggered. So, keep track of the previous state and the new state. When the previous state is 'buffering' and the new state is 'ended', 'playing', or 'paused', then this means that the video finished buffering.
Here is an example:
<html>
<body>
<div id="player"></div>
<script>
var player;
var lastState;
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
if (lastState == YT.PlayerState.BUFFERING &&
(event.data == YT.PlayerState.PLAYING || event.data == YT.PlayerState.PAUSED)) {
alert('Buffering has completed!');
}
lastState = event.data;
}
</script>
</body>
</html>