Reputation: 391
I'm reading the "iframe_api_reference" and I want to make something like a playlist that plays the next video after the actual video ends, so...
Based on this:
<div id = "player" style = "height: 390; width: 590;"></div>
<script src="http://www.youtube.com/player_api"></script>
<script>
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '590',
videoId: "4kpXVR6LavI",
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
if(event.data === 0) {
alert("over");
}
}
</script>
I want to take the next video from something like this:
<div class="youtube" id="4kpXVR6LavI">
<p>Video title</p>
<img src="portraitphoto" alt="">
</div>
How I can make this? Thank you!
Upvotes: 1
Views: 683
Reputation: 4950
You need to add event listener to your app. player.addEventListener(event:String, listener:String):Void
. The listener is a string that specifies the function that will execute when the specified event fires.
Include onStateChange
, this event fires whenever the player's state changes. The value that the API passes to your event listener function will specify an integer that corresponds to the new player state.
function onYouTubePlayerReady(playerId) {
ytplayer = document.getElementById("myytplayer");
ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}
function onytplayerStateChange(newState) {
alert("Player's new state: " + newState);
}
Bind your custom function as the handler to the "onStateChange"
event, and evaluate the new state from within. According to the Events portion of the API, you're looking for state 0
, indicating the video has ended.
function onytplayerStateChange(newState) {
if ( newState == 0 ) {
/* load next video */
}
}
Upvotes: 1