Reputation: 97
I have read the basics of the YouTube API and have it working on my webpage with no problems. However I would like to be able to use the video's state to trigger or stop certain functions which I have written in an external JS file. I'd really appreciate any help!
At present I have the following embedded into my HTML file just after the iframe itself:
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('MyVideoID',{
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event){
event.target.playVideo();
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
var slideTimeMS = 10000; /* This is a variable which exists in my external file which I would like the player state to manipulate
}
}
The code above in itself works fine but as I said before I would like to move it to an external file so I can, for example, pause a carousel when the video is playing etc., the functions for which are already in said JS file.
Can anyone tell me how I could successfully make this accessible in the other file?
Thanks so much for any help!
Mark
Upvotes: 1
Views: 2197
Reputation: 11
this article was very useful for me
window.onYouTubeIframeAPIReady = function() {
window.player = new window.YT.Player(iframeId, {
......
});
}
Upvotes: 1
Reputation: 97
For anyone who this might help, here was the solution I eventually found:
Iframe embedded in HTML as normal but with no JS done in the HTML whatsoever. In my JS file I have the following:
var myPlayerState;
$(function(){
var yt_int, yt_players={},
initYT = function() {
$("IDOrClassOfMyVideo").each(function() {
yt_players[this.id] = new YT.Player(this.id,
{
events: {
'onReady' : onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
});
};
$.getScript("//www.youtube.com/player_api", function() {
yt_int = setInterval(function(){
if(typeof YT === "object"){
initYT();
clearInterval(yt_int);
}
},500);
});
Then the functions in the rest of the code work as normal!
Upvotes: 4