Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding event callback for YouTube JS Player API when related video clicked

YouTube's iFrame embed JS player API allows you to add callbacks to certain events. I want to add a callback for when a related video at the end of a video is selected.

To be more specific, when viewing a video in an embed, at the end it displays related videos within the embed. I want to run some code when one of those is selected. How can this be accomplished? I see that there is an onStateChange but none of the states are related to related videos. Do I need to add an onStateChange for YT.PlayerState.PLAYING and then compare the playing video to the original video to see if they're different somehow?

like image 653
Mike Crittenden Avatar asked Jan 22 '26 02:01

Mike Crittenden


2 Answers

That seems like a reasonable solution to me.

The only point worth mentioning (which you've noted) is that you will be not able to tell if the change in the video is due to the user clicking on a related video, but if you're not interacting with the player dynamically, comparing the previous VideoID should suffice.

Just a heads up, if you're interested in a jQuery plugin that simplifies some of the callback/event handling work check out: https://github.com/nirvanatikku/jQuery-TubePlayer-Plugin

like image 90
Nirvana Tikku Avatar answered Jan 23 '26 15:01

Nirvana Tikku


I ended up doing it basically the way I described. Here's the code I used:

started = false;

var onYouTubeIframeAPIReady = function(id) {
  var player = new YT.Player('player', {
    videoId: id,
    events: {
      'onStateChange': function (event) {
        if (event.data == 1) { // The video started playing
          started = true;
        }
        if (started && event.data == -1) {
          // Video had already started playing before and is now in
          // "unstarted" state so it must be a new video.
          var video_url = event.target.i.videoUrl;
          var video_id = video_url.replace('http://www.youtube.com/watch?v=', '').replace('&feature=player_embedded', '');
          window.location = '#/view/' + video_id;
        }
      }
    }
  });
}

So basically, when a video starts playing, you set a "started" variable to true. Then, if/when the video enters the "unstarted" state, if "started" is true, then you know that it's a new video that just started playing. In that case, grab its video ID from the event.target object and do whatever you want with it.

My full commit is here if anyone wants to see the context and you can see it in action on http://toogl.es.

like image 32
Mike Crittenden Avatar answered Jan 23 '26 15:01

Mike Crittenden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!