Search code examples
javascriptyoutubeyoutube-apiyoutube-iframe-api

Detect when video has changed - YouTube iFrame API


I have some kind of slider with a YouTube playlist in the background. I'd like to know when the video has changed, so I can change the slider text to the right text.

I've searched the API page (https://developers.google.com/youtube/iframe_api_reference#Events) and can't seem to find an event that fires when the video changes. Is there one?

Here's my code until now.

var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

window.player;
var player;

var playlistVideos = new Array();
jQuery('#playlistSlider span').each(function(){
    playlistVideos.push(jQuery(this).html());
})

//console.log(playlistVideos)

function onYouTubePlayerAPIReady() {
    player = new YT.Player('playlistSlider', {
        height: '390',
        width: '640',
        loadPlaylist:{
            listType:'playlist',
            list:playlistVideos,
            index:parseInt(0),
            //suggestedQuality:'small'
        },
        events: {
            'onReady': onPlayerReady,
            //'onStateChange': onPlayerStateChange
        },
    });
}
function onPlayerReady(event) {
    event.target.loadPlaylist(playlistVideos);
    event.target.mute();
    event.target.setLoop(true);
}

A bonus would also be to know what is the current video playing (index).


Solution

  • Listen for the player's onStateChange callback.

    events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
    }
    

    If the event value is 0, the video has ended

    function onPlayerStateChange(event) {
        if (event.data == 0) {
            // video ended
        }
    }
    

    For knowing the index of the current playing video, keep a variable index which is initially set to 0. As the current video ends and the next one loads, increment your index by one. The index value will point to the current video in your playlistVideos.