Question

Made a droppable/sortable where you can drag and drop YouTube videos (see #Playlist li). Trying to get it so that when you click on a video, and it plays and ends, it loads the next video immediately after. Past week I've tried for loops, $.each, and $().each(), and each time my code just plays the last video (i.e. clicks the last element) in the list. It also doesn't seem to execute the function if I append more videos to the end of the list, i.e. when the video that was previously the last in the list ends, it doesn't load any of the new videos.\

Sure I'm missing something simple, but I can't see it. Here's the code:

var playlistItems = $('#Playlist li');

$(playlistItems).each( function(index, value){
  $(value).click(function(){
          videoID = $(value).find('img').attr("src").slice(27,38);
          player.loadVideoById(videoID );
          nextVideo = $(value).next().find('img');
          player.addEventListener('onStateChange', function stopCycle(event) {
            if (event.data == YT.PlayerState.ENDED) {  

            $(nextVideo).click();
 }
            }
);});}
Was it helpful?

Solution

try replacing the code posted in your question with this. Just a warning, it kind of assumes other parts of your code are working.

$(document).on('click', '#Playlist li', function(){
      var videoID = $(this).find('img').attr("src").slice(27,38);
      player.loadVideoById(videoID);
      var nextVideo = $(this).next().find('img');
      player.addEventListener('onStateChange', function stopCycle(event) {
          if (event.data == YT.PlayerState.ENDED) {
              $(nextVideo).click();
          }
      });
});

basically, you don't even need the each loop. this handles any li living in #PLaylist ever by delegating the event.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top