Reputation: 9495
I have created a page with the following code to detect state changes to a YT iFrame embed. The player detects the onReady
event but not the onStageChange
event.
Can anyone explain what I'm missing here?
https://codepen.io/anon/pen/LOZVoX?editors=1001
Code:
<iframe id="yt-iframe" width="630" height="354" src="http://www.youtube.com/embed/CTFtOOh47oo?rel=0&?enablejsapi=1" frameborder="0" allowfullscreen=""></iframe>
<script type="text/javascript">
var tag = document.createElement('script');
tag.id = 'yt-iframe';
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
console.log('yt scripts loaded');
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('yt-iframe', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
console.log('video player ready');
}
function onPlayerStateChange(event) {
console.log('state has changed');
console.log(event.data);
}
</script>
Upvotes: 1
Views: 1362
Reputation: 3622
You have 2 mistakes on your code.
First of all your video url parameters are not correct.
Your url is http://www.youtube.com/embed/CTFtOOh47oo?rel=0&?enablejsapi=1
, thus you pass the parameters rel
and amp;?enablejsapi
.
Instead your link should be http://www.youtube.com/embed/CTFtOOh47oo?enablejsapi=1
, with the parameter enablejsapi
.
Your second mistake is that you set your yt script's id to be the same with your iframe's id.
Change the id of the yt script to something else like tag.id = 'yt-script';
.
https://codepen.io/anon/pen/yPJJbv?editors=0001
Upvotes: 1