Using the YouTube JavaScript API to Play Random Videos

I’ll get this YouTube thing working the way I want.

I didn’t want to be beholden to a pre-defined YouTube playlist, but I did want some hot, random video play action to take place after the initial video provided on page load finished.

A nice way to do this is to do the following:

  1. I serve up a page with the typical YouTube <IFRAME> embed in place.
  2. Make sure you have the enablejsapi=1 parameter set in the SRC request for the video. Also, give the <IFRAME>a nice ID attribute.
  3. Then in the JavaScript, I target the <IFRAME>by its ID and instantiate a player object.
  4. Let that video play its buns off.
  5. For the video “done” callback, when you instantiate that player, make sure to get some event handlers going.  Something like:
    function onYouTubeIframeAPIReady() { player = new YT.Player('PLAYER IFRAME ID', { events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange } }); }
  6. At this point you can get that video ID from a long list, or have some API or feed give it to you, maybe rip it from Tweets or something?  Who knows… anyhow, just have that ID ready.
  7. The following will get the next vid ready and play it when the first one ends:
    function onPlayerStateChange(event) { if(event.data === 0) {player.loadVideoById(DESIRED_VIDEO_ID); player.playVideo();}