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?
I ended up doing it basically the way I described. Here’s the code I used:
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.