0

Currently trying to detect when a YouTube video in a playlist ends so I can play the next one ( Adding event handler to loop through dynamically created playlist (YouTube API) ). I'm now trying to figure out when one variable is equal to another, so I can navigate to the next video in the playlist.

Here is the code to detect when a video has ended and save the video ID to a div (stopID):

function stopCycle(event) {
      if (event.data == YT.PlayerState.ENDED) {
           var url = event.target.getVideoUrl();
           var match = url.match(/[?&]v=([^&]+)/);
           var videoId = match[1];
           $('#stopID').html(videoId);
      }
  }

And here is my attempt at detecting (and testing with an alert) when the video ID of the video clicked equals the video ID of the in stopCycle (i.e. when the video ends):

    $('#Playlist').on('click', '.playlistYT', function(){
       $('#subHistory').click();
       videoID = $(this).attr("src").slice(27,38);
       $('#infoID').val(videoID);
       player.loadVideoById(videoID ); 
       var nextVideo = $(this).parent().next().find('.playlistYT');

      $.when($('#stopID').html() == videoID).then(function(){
          alert("asd");
      });

Currently, I get the alert immediately, i.e. before the stopID div even has a video ID in it. Where am I going wrong with $.when function? Should I be sticking to an if/else statement?

Community
  • 1
  • 1
Amir
  • 281
  • 5
  • 15
  • Please, read the DOC! – A. Wolff Mar 15 '14 at 14:56
  • This is what I was reading, but I don't quite understand: https://api.jquery.com/jQuery.when/ . If there's a more basic tutorial I'd be happy to read that. – Amir Mar 15 '14 at 15:00
  • And did you read the description at the top "Provides a way to execute callback functions ... usually Deferred objects that represent asynchronous events." – adeneo Mar 15 '14 at 15:11
  • Started going through Deferred objects on jquery docs after I read that bit, and assumed it was to do with objects called on ajax? That's how most of the examples seem to work, so I assume it isn't relevant for this code which is why I put a question mark by the use of $.when, but the if conditional doesn't seem to be working. – Amir Mar 15 '14 at 15:14

1 Answers1

1

$.when takes in a promise argument. Just use an if conditional to check equality.

edhedges
  • 2,722
  • 2
  • 28
  • 61
  • I tried if($('#stopID').html() == videoID)(function(){ alert("asd"); } beforehand and that didn't work at all :/ – Amir Mar 15 '14 at 14:59
  • Sorry, I mean: if($('#stopID').html() == videoID){ alert("asd"); } – Amir Mar 15 '14 at 15:05
  • Read the docs. Also use console.log or browser developer tools to see what the values actually are for the two things you are checking for equality. – edhedges Mar 15 '14 at 15:06