How to use the YouTube iFrame Player API: Control videos with JavaScript

- Andrés Cruz - ES En español

How to use the YouTube iFrame Player API: Control videos with JavaScript

Continuing with the APIs series, now it's the turn of the giant Google and its YouTube platform, which serves for much more than playing music and watching cat videos. YouTube has an API available for JavaScript from which we can have great control over the videos embedded in our website.

Embedding YouTube videos into a web page is simple... until you need absolute control over what happens inside the player. That is where the YouTube IFrame Player API comes in—a tool I discovered after working with other audio APIs that allowed me to go from simple embeds to controlling videos as if they were my own: play, pause, detect states, automate playlists, and even chain multiple videos without manually touching an iframe.

In this guide, I take you from scratch to advanced uses, with real-world examples and problems I faced myself when implementing it.

What is the YouTube IFrame Player API and what is it for

YouTube offers an API that allows you to create players dynamically with JavaScript, instead of the classic copy-and-paste of an iframe. This unlocks features such as:

  • Play, pause, fast forward, or change volume via code
  • Detect when a video ends (crucial for automatic playlists)
  • Switch one video for another without reloading the page
  • Customize controls, colors, subtitles, theme, and player behavior
  • Create fully customized playlists from your own data

With the API, intervening in the video's behavior is very simple. For example, in one of my projects I had a list of songs in HTML and needed the next one to load automatically when one finished without user intervention. With this API, I solved it in a few lines using the onPlayerStateChange event and the loadVideoById method.

How it differs from the traditional iframe

The fundamental difference is the level of programmatic control you get. With an iframe copied directly from YouTube, you simply embed the video and that's it: you cannot know if it finished, you cannot change it, you cannot react to anything. The IFrame Player API converts that static player into a fully operable JavaScript object:

  • Copy/paste iframe: very limited control, ideal for blogs or simple embeds
  • IFrame Player API: total control, recommended for interactive websites, custom players, and JavaScript applications

How to include the YouTube IFrame Player API in your website

The first thing you must do is load the API script. You can do this synchronously with a standard script tag using either of these two equivalent URLs:

<script src="https://www.youtube.com/iframe_api"></script>

The URL http://www.youtube.com/player_api also works, but it is recommended to always use https://www.youtube.com/iframe_api for security and consistency with the official documentation.

Synchronous loading vs. asynchronous loading

Including the script directly in the HTML blocks page rendering until the file is downloaded and executed. To avoid this, Google's own documentation recommends inserting the script asynchronously using JavaScript:

var tag = document.createElement("script");
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

This pattern creates the script element at runtime and inserts it before the first existing script on the page, ensuring that the API loads without blocking rendering. Once the script finishes loading, the API automatically calls the global onYouTubeIframeAPIReady function, which is where we initialize our player.

How to load a YouTube video with JavaScript

Once the library is included, the next step is to initialize the player inside the onYouTubeIframeAPIReady function. This function is the entry point for the entire API: YouTube calls it automatically as soon as the script is ready, so any code that depends on the player must live here or be invoked from here.

var player;

function onYouTubeIframeAPIReady() {
  player = new YT.Player("player", {
    width: 640,
    height: 390,
    videoId: "VIDEO_ID_HERE",
    events: {
      onReady: onPlayerReady,
      onStateChange: onPlayerStateChange,
    },
  });
}

The new YT.Player() constructor takes as its first argument the id of the HTML element where the player will be mounted (in this case "player"), and as its second a configuration object with dimensions, the videoId of the video you want to load, and the events you wish to subscribe to.

Controlling the player with JavaScript

When creating the player, we register two fundamental events: onReady, which fires when the player is fully loaded and ready to receive commands, and onStateChange, which triggers every time the video changes state (for example, when playback ends). The basic implementation for both would be:

function onPlayerReady(event) {
    event.target.playVideo();
}

function onPlayerStateChange(event) {
    if (event.data === YT.PlayerState.ENDED) {
        // the video finished, here you can load the next one
    }
}

Inside onPlayerStateChange, the event.data property contains an integer representing the current state of the player. The API exposes these constants through the YT.PlayerState object, although you can also compare directly with the numeric values:

  • -1YT.PlayerState.UNSTARTED: unstarted
  • 0YT.PlayerState.ENDED: playback ended
  • 1YT.PlayerState.PLAYING: playing
  • 2YT.PlayerState.PAUSED: paused
  • 3YT.PlayerState.BUFFERING: buffering
  • 5YT.PlayerState.CUED: video cued (queued but not played)

How to react when a video ends (ENDED state)

The most common use case for onPlayerStateChange is detecting the end of a video to automatically load the next one. State 0 (or YT.PlayerState.ENDED) is your signal to act. Using the loadVideoById method, you can switch the video in the same player without reloading anything:

function onPlayerStateChange(event) {
    if (event.data === YT.PlayerState.ENDED) {
        event.target.loadVideoById({
            videoId: nextVideoId,
        });
    }
}

How to create an automatic playlist with the YouTube IFrame API

One of the most powerful features of the API is chaining videos automatically based on your own data, without relying on YouTube playlists. The trick is to listen to the onStateChange event with event.data === 0 (video ended) and use loadVideoById to load the next video from your list.

In the following example, the identifier for the next video is retrieved directly from a data-href attribute of an HTML list item, allowing you to build completely dynamic playlists managed from your own HTML or database:

function onPlayerStateChange(event) {
    if (event.data === YT.PlayerState.ENDED) {
        index++; // moves to the next element in the list
        event.target.loadVideoById({
            videoId: $($('.lista_canciones li')[index]).attr("data-href")
        });
    }
}

With this, you have the basic elements to create your own automated and customized playlist from your website. If you want to dive deeper into all available parameters, you can consult the official documentation: YouTube Player API Reference for iframe Embeds.

Essential methods to control the player

Once you have the player variable initialized, you can invoke these methods at any time from your JavaScript code:

player.playVideo();          // start playback
player.pauseVideo();         // pause
player.stopVideo();          // stop and reset
player.seekTo(30, true);     // seek to 30 seconds
player.setVolume(50);        // volume from 0 to 100
player.getCurrentTime();     // current time in seconds
player.getDuration();        // total duration of the video
player.getPlayerState();     // current state (see table above)

Quick reference of the most used methods of YT.Player:

  • playVideo() → start playback
  • pauseVideo() → pause
  • seekTo(seconds, allowSeekAhead) → seek to a specific point in the video
  • loadVideoById(videoId) → change video in the same player
  • cueVideoById(videoId) → load video without playing it automatically
  • getPlayerState() → check current player state
  • getCurrentTime() → get current playback time in seconds
  • setVolume(volume) → set volume (value between 0 and 100)

Advanced player options: playerVars

When creating the YT.Player object, you can pass a playerVars property with a set of parameters that control the behavior and appearance of the player. These are the most useful:

  • autoplay: 1 to play automatically upon loading
  • controls: 0 hides controls, 2 shows them always
  • start / end: exact start and end seconds for playback
  • rel: 0 to limit related videos to the same channel
  • modestbranding: 1 to minimize the YouTube logo
  • playsinline: 1 to play inline on iOS without triggering fullscreen
  • playlist: comma-separated list of video IDs for sequential playback
  • loop: 1 to loop the video or playlist
  • color: "white" or "red" for progress bar color
  • cc_load_policy: 1 to automatically show captions

Full initialization example with playerVars:

player = new YT.Player("player", {
    width: 640,
    height: 390,
    videoId: "VIDEO_ID_HERE",
    playerVars: {
        autoplay: 1,
        controls: 2,
        modestbranding: 1,
        rel: 0,
        playsinline: 1,
        start: 10,
        end: 120,
    },
    events: {
        onReady: onPlayerReady,
        onStateChange: onPlayerStateChange,
    },
});

Real-world use cases for the YouTube IFrame Player API

  • Automating sequential playback
    • When I was developing a song list, I needed the next song to start automatically when one finished. The API solved it with event.data === 0 and loadVideoById in just a few lines of code.
  • Loading videos based on user selection
    • I achieved changing the player's video instantly upon clicking any element in the DOM without reloading the page, using loadVideoById combined with a DOM event listener.
  • Improving user experience (UX)
    • The onReady event notified me when the video was fully loaded and ready, allowing me to display a "loading" animation in the UI while waiting and hide it at the exact moment the player became available.
  • Integration in academies and e-learning platforms
    • I use this API on my own Academy platform to manage course videos hosted on YouTube. Control over the player state allows me to record student progress, block progression if the video hasn't finished, or trigger automatic actions upon completing a lesson.

Frequently Asked Questions (FAQ)

  • Do I need to know a lot of JavaScript to use the IFrame Player API?
    • No. With basic knowledge of functions and callbacks, you can manage perfectly well. The official documentation is clear, and the examples in this guide cover the most common cases without requiring additional frameworks or libraries.
  • What is the difference between the IFrame API and the YouTube Data API?
    • They are distinct APIs with different purposes. The IFrame Player API controls the player: play, pause, volume, states. The YouTube Data API v3 handles data: searches, video metadata, playlists, uploading videos, managing comments, etc. To play and control videos on your site, the one you need is the IFrame API.
  • Can I completely avoid related videos when a video ends?
    • Not 100%, as YouTube changed its policy in 2018 and no longer allows hiding them completely. However, using rel=0 in playerVars limits related videos to those from the same channel, which significantly improves behavior. An alternative is detecting the ENDED state and loading the next video immediately so the suggestions screen barely appears.
  • Does the onYouTubeIframeAPIReady function need to be global?
    • Yes, it is an API requirement. This function must be available in the global scope (window.onYouTubeIframeAPIReady), as the YouTube API calls it directly once its script finishes loading. If you define it inside a module or with const/let in a local scope, the API will not find it, and the player will never initialize.

Conclusion

The YouTube IFrame Player API is a powerful tool for any web project that needs to manage videos beyond the typical static iframe. I use it on my Academy platform to manage course videos hosted on YouTube with full control over the player.

With it, you can:

  • Create dynamic and fully programmable players
  • Detect and react to video states (PLAYING, PAUSED, ENDED…)
  • Automate custom playlists without depending on YouTube
  • Improve UX with loading animations and transitions between videos
  • Integrate YouTube videos professionally into any JavaScript application

If you already have your own UI structure or data lists in your application, this API will allow you to connect everything with a flexible, controllable player that integrates seamlessly with your code.

IFrame Player API for playing, pausing, detecting states, and creating automatic playlists with JavaScript. Guide with real-world examples of loadVideoById, onYouTubeIframeAPIReady, and playerVars.


Únete a la comunidad de desarrolladores que han decidido dejar de picar código y empezar a construir productos reales. Recibe mis mejores trucos de arquitectura cada semana:

I agree to receive announcements of interest about this Blog.