Embed a YouTube video player and control it via JavaScript

YouTube has long made it easy to share and embed videos into websites by giving you the HTML code to just copy and paste wherever you like. Over the years, different technologies have been used to play videos on the web, from Flash object elements to pure HTML5. YouTube's newest API for adding videos to web pages takes care of the technology, automatically choosing the best delivery method on a user by user basis.

YT did have something called the "YouTube JavaScript Player API" but this is out of date so don't use it. Instead use the new YouTube IFrame Player API, so called because it creates an iframe which loads YouTube and lets YT handle loading the right code, e.g.. Flash if it's needed.

With this API, you can programmatically load videos (or even lists of videos), step into them in the middle of the video if you wish instead of just the beginning, and play the video triggered by JavaScript. This means you could have a video playing when the page loads, or seconds after the page loads, or triggered by events like scrolling down or pressing keys or clicking the mouse. You can really control the video player however you want and can create your own custom interface for it.

  1. Get a player object with YT.Player.
  2. Load a video into the player: loadVideoById (pass in videoId, which you can get from the video's URL).
  3. Play it! player.playVideo()

There are two problems with YouTube control under JavaScript. A big one is that iOS Safari doesn't support it! JavaScript on Safari cannot cause a YouTube player to play or be controlled. If you need something that works for iPhone/iPad users, then you need to just show them a normal embedded YouTube player and tell them to play it themselves. You can't create a custom player interface for them.

Another problem with YouTube JavaScript on mobile is timing. Mobile browsers (like Chrome on Android) are running JavaScript slower than desktops to begin with. There's also the issue of buffering videos. I've found that smartphones using the same web code and the same Internet connection buffer more often when playing a video. You can detect buffering by subscribing to the player's onStateChange events, which will fire when the player starts playing, is paused, and also when buffering.

Even when accounting for buffering, I've found that the player's events can be delayed significantly, or that player actions happen significantly before the events fire. If you are trying to control the player using timers (setTimeout) then you'll be off by a second or more on mobile.

If you want to play a segment of a video (e.g. seeking to time 31.5 seconds and playing for 28.5 seconds) then you can achieve it more accurately using the arguments passed in when you load the video. Use the options startSeconds and endSeconds.