View on GitHub

YouTube iframe API Tutorial

This tutorial will teach you how to embed a YouTube video player on your website and control the player using JavaScript

YouTube API Home ☰ Menu

The Basics of YouTube API

By: Melissa Barr


Introduction

What is the YouTube IFrame API?

The Iframe player API is a program that lets you embed a YouTube video player into your website and lets you program it to your specifications using JavaScript. There are many ways to personalize it.

For example you can:
1. Play
2. Pause
3. Stop
4. Adjust player volume
5. Retrieve information about the video
6. Add event listeners

I choose to do this program because it is a useful tool that can be added to any website either to support information, explain ideas, or just for fun!

Here is where you can find the software and existing documentation for the YouTube IFrame API. Credit is given for code experts. https://developers.google.com/youtube/iframe_api_reference



Getting Started: How do you set it up?

Requirements

There are a few requirements that you need:

  • A browser that supports the HTML5 postMessage feature (most browsers do but keep in mind that Internet Explorer 7 does not support this)
  • The player must have an area at least 200px by 200px to play the video and if you decide to include controls then it must have room for that as well
  • Must use the onYouTubeIframeAPIReady function - we will explain more on this later


  • Here is a sample HTML code that creates an embedded player that will load a video. Code explained below.

    YouTubeAPI

    So lets talk about what’s going on here.

    Starting at the top at #1, the <div> tag is used to get the location on the page of where the video player will be placed. This is identified by the id to make sure that the <iframe> places it in the correct location.

    Continuing on to #2, this is the part of the code that actually loads the Iframe Player API JavaScript code. The <script> part is needed to asynchronously download the code. It is important to keep in mind that this is not yet supported in all modern browsers.

    Remember when we mentioned the onYouTubeAPIReady function before? This is where it comes into play. It is used to execute the code as soon as the player downloads. What is is actually doing is contracting a video player object but to phrase that in easier to understand terms it is defining the terms of the player and getting ready to play the video. There are a few ways to personalize this which we will go into detail in a bit but as shown you can specify the height, width, and when it plays.

    While the previous function gets the video ready to play, the onPlayerReady function plays the video when it is ready. Again, this depends on the settings you have programmed it to.

    Lastly #5 is all about changing the state of the player. The onPlayerStateChange function is for when the state of the player changes. This includes any of the 6 ways to personalize the video player shown in the introduction as well as more!

    In this example specifically, you can see the number 6000. This means that the video will start playing and after 6 seconds the video will call the function stopVideo() and the player will stop it. As you can see from the video playing at the top of the website, it does not have this restriction on it because it is able to play throughout the whole video.

    JavaScript

    All of the research I have done shows that using the HTML iFrame code is the easiest and fastest option however there is the JavaScript route as well. In fact the HTML code actually loads the Iframe player API JavaScript code so they make it very convenient when trying to embed a video. In fact you need to have it load this because you have to use JavaScript in order to control the player. The onYouTubeIframeAPIReady function is what is called when the page has finished downloading the JavaScript for the player API.



    Video Player: How do you interact with it?

    Loading a Video

    Now that we have the basics down we can make adjustments to personalize the video player even more! Here is the code shown in #3 above but posted again to make it easier to follow.

    YouTubeAPIVideoExample
    There are two parameters to consider here:
    1. The first parameter specifies either the DOM element of the id or the HTML element
    2. The second parameter specifies the video player options

    In simpler terms, the first parameter replaces it with the iframe element which contains the player. Keep in mind that this can also change the layout of the page if the parameter replaced has a different display style than the iframe.

    The second parameter is where all of the personalizing comes in. The object contains 3 main properties:

    </tr>
    Property Function
    width This is a number and specifies the width of the video player. (Default: 640)
    height This is a number and specifies the height of the video player. (Default: 390)
    videoId This is the ID of the video that will play. It can be found at the end of the url. (Ex: for https://www.youtube.com/watch?v=0HTexqxo1og then "0HTexqxo1og" is the ID of the video.

    The onPlayerReady event ensures that the video will start when the page opens which is shown here by the video in the beginning.

    Functions

    Queueing Functions

    Now that we can get our video up and running what if we want to not play it immediately? For example wait 5 seconds to start the video. This is where functions come in. We will only touch briefly on this because it the information on this goes into great detail and we are looking more at the main idea.

    There are 2 types of syntax that make this happen.

  • Argument syntax
  • loadVideoById("bHQqvYy5KYo", 5, "large")

  • Object syntax
  • loadVideoById({'videoId': 'bHQqvYy5KYo', 'startSeconds': 5, 'endSeconds': 60, 'suggestedQuality': 'large'});

    The API supports the two different types of syntax. The first type, argument syntax, requires that the function arguments be listed in order. The second type, object syntax, lets you pass an object as a single parameter to define the properties and may support additional things that the argument syntax does not.

    If you want to start the video 5 seconds in and not end it at a certain time then argument syntax is the way to go. If you want to start the video 5 seconds in and end it after 60 seconds then object syntax gives the option to do that.

    Functions

    Without going into too much detail, a brief overview of other functions available include the following. Keep in mind that each of these also have options for argument syntax as well as object syntax.

    </tr>
    Function Description
    cueVideoById This function loads the video’s thumbnails and prepares the player to play the video
    loadVideoById This function loads and plays the specified video
    cueVideoByUrl This function does the same this as cueVideoById but uses an URL
    loadVideoByUrl This function does the same thing as loadVideoById but uses an URL

    You can even make functions for playlists! Both of the following functions allow you to play a playlist of videos. Each work a little differently and therefore have different properties.

    Function Code Description
    cuePlaylist player.cuePlaylist(playlist:String|Array, index:Number, startSeconds:Number, suggestedQuality:String):Void This function queues the specified playlist. It takes an array of YouTube video IDs and an optional parameter to play the first video in the playlist. Again you can customize it with the startSeconds and suggestedQuality
    loadPlaylist player.loadPlaylist(playlist:String|Array, index:Number, startSeconds:Number, suggestedQuality:String):Void This function loads the specified playlist and plays it. Again it takes an array of video ID’s with the optional parameter with startSeconds and suggestedQuality.

    Playback Controls


    Playing a Video

    Up until now we have talked about getting the player set up with basic functions. Now we want to look at ways to customize how it plays the video. There are a lot of different options here. We also can look at what the final player state is after the function executes.

    Function Description Final Player State
    player.playVideo():Void Plays the currently cued video playing(1)
    player.pauseVideo():Void Pauses the currently playing video paused(2)
    player.stopVideo():Void Stops video and stops loading of the video. Warning: This function is not used often and should only be used when you know the user will not be watching any additional videos in the player Can put the player into any non-playing state

    Playing a video - Playlist

    Function Description
    player.nextVideo():Void This function loads and plays the next video in the playlist. It can even be set to continuously loop or just end
    player.previousVideo():Void This function load and plays the previous video in the playlist. Again can be set to a loop
    player.playVideoAt(index:Number):Void This function loads and plays the specified video in the playlist. Keep in mind you have to include an index parameter because you have to specify the index of the video that you want to play

    There are many more ways to personalize the video player but here are a few generally listed:

    Changing the Player Volume
    1. player.mute():Void
    2. player.unMute():Void
    3. player.isMuted():Boolean
    4. player.setVolume(volume:Number):Void
    5. player.getVolume():Number
    Setting the player size
    1. player.setSize(width:Number, height:Number):Object
    Setting the playback rate
    1. player.getPlaybackRate():Number

    Playing a video - Playback Status

    Often the functions return a status which usually comes in the form of a number. Here are the possible values and what they mean.

  • -1 – unstarted
  • 0 – ended
  • 1 – playing
  • 2 – paused
  • 3 – buffering
  • 5 – video cued

  • Event Handlers

    Last thing to address is Events. At this point you should have a good understanding on how to get everything set up and personalized. There are many different types of events, all however are equally important.

    Event Handlers Description
    onReady onReady This event fires when a player has finished loading. A good example is playing the video automatically. As you can tell from the video when this website loaded, it has been coded with the onReady event.
    onPlaybackQualityChange This event fires when the video playback quality changes. The data property value possible values are:
    • small
    • medium
    • large
    • hd720
    • hd1080
    • highres
    onPlaybackRateChange This event fires whenever the video playback rate changes
    onError This event fires if an error occurs in the player. Here are a few possible errors that could occur:
    • 2 - if the request contains an invalid parameter value
    • 5 - any error associated with HTML5, such as the HTML5 player not supporting the video
    • 100 - the video requested was not found
    • 101 - the owner of the video does not allow it to be played in an embedded player
    • 150 - the error is the same as 101


    Example Video

    The example video is shown at the top of the page!