Youtube Api Onstatechange Listener Stops Working After Switch Src Attr
I am trying to change the video playing in the YouTube iframe in the cleanest way possible and a few months ago I had this code working, but YouTube changed their API and it stoppe
Solution 1:
Try this instead :
<!DOCTYPE html><html><body><scriptsrc="jquery-1.10.2.min.js"></script><!-- 1. The <iframe> (and video player) will replace this <div> tag. --><divid="player"></div><buttonclass="button"data-youtubeid="b-3BI9AspYc">BUTTON</button><script>// 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);
// 3. This function creates an <iframe> (and YouTube player)// after the API code downloads.var player;
functiononYouTubeIframeAPIReady() {
player = newYT.Player('player', {
height: '390',
width: '640',
videoId: '0Bmhjf0rKe8',
playerVars: { 'autoplay': 1, 'controls': 1 },
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
var playerReady = false;
// 4. The API will call this function when the video player is ready.functiononPlayerReady(event) {
playerReady = true;
}
// 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.functiononPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED ) {
alert('done');
}
}
$(".button").on("click", function(){
player.loadVideoById("Vw4KVoEVcr0", 0, "default");
});
</script></body></html>
The fiddle here : http://jsfiddle.net/QtBlueWaffle/8bpQ8/1/
Hope this helps
Solution 2:
I had kind of the same problem (I Think)... I wanted the user to be able to change the content for multiple players, and this is what works for me: I call the youtube api with a onload function additional to the new Youtubelink, so that reloads every time the iframe changes.
MY HTML:
<iframe onload="floaded1()"id="player1" width="240" height="220"
src="http://www.youtube.com/embed/0Bmhjf0rKe8
?enablejsapi=1&rel=0&showinfo=2&iv_load_policy=3&modestbranding=1"
frameborder="0" allowfullscreen> </iframe>
MY JS:
function floaded1() {
player1 = new YT.Player('player1', {
events: {
'onStateChange': function (event) {
if (event.data == 0) {
alert('done');
};
}
}
});
}
WHAT I LOAD WITH A VIDEO PICKER:
html += '<iframe onload="floaded1()" id="player1" width="240" height="220"
src="http://www.youtube.com/embed/'+YouTubeVideoId+'?enablejsapi=1&rel=0&
showinfo=2&iv_load_policy=3&modestbranding=1" frameborder="0" allowfullscreen>
</iframe>';
Post a Comment for "Youtube Api Onstatechange Listener Stops Working After Switch Src Attr"