How to use the YouTube iFrame Player API in JavaScript to load and play videos with JavaScript
- 👤 Andrés Cruz
Continuing to work with APIs, it's now the turn of the giant Google and its YouTube platform, which is useful for much more than just playing music and watching cat videos... YouTube has an API available for JavaScript from which we can have great control over YouTube videos embedded on our website.
Embedding YouTube videos on a website is simple... until you need absolute control over what happens inside the player. That's where the YouTube IFrame Player API comes in, a tool I discovered after working with other audio APIs that allowed me to move from simple embeds to controlling videos as if they were my own: playing, pausing, detecting states, automating playlists, and even chaining several videos without manually touching an iframe.
In this guide, I'll take you from scratch to advanced uses, with real examples and problems I faced when implementing it myself.
What the YouTube IFrame Player API is and what it's for
YouTube offers an API that allows you to create players dynamically with JavaScript, instead of the classic copy-paste iframe. This unlocks features such as:
- Play, pause, seek forward, or change volume
- Detect when a video ends (crucial for automatic playlists)
- Change one video for another without reloading the page
- Change controls, colors, subtitles, theme, etc.
- Create custom playlists from your own data
With the API, it's very simple to intervene in the video's behavior. For example, in one of my projects, I had a list of songs in HTML and needed the next one to load automatically without user intervention when the current one finished. With this API, it was trivial.
How it differs from traditional iframe embedding
The IFrame Player API gives you a programmable player:
- Method Control Level Recommended for
- Copy/paste iframe Very limited Blogs, simple embeds
- IFrame Player API Total control Interactive websites, custom players, JS apps
Including the JavaScript API on our website
The first thing we must do is include this API, which is simply a JavaScript file:
<script src="http://www.youtube.com/player_api"></script>Or
<script src="https://www.youtube.com/iframe_api"></script>Synchronous load vs asynchronous load
Recommendation: use asynchronous loading so as not to block your website:
var tag = document.createElement("script");
tag.src = "https://www.youtube.com/iframe_api";
var first = document.getElementsByTagName("script")[0];
first.parentNode.insertBefore(tag, first);Loading a YouTube video
Once our library is included, the next thing we have to do is load a video programmatically with JavaScript using the following JavaScript code:
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player("player", {
width: 640,
height: 390,
videoId: "VIDEO_ID_AQUI",
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange,
},
});
}Controlling the player with JavaScript
We immediately define two events that will execute once the YouTube video is ready and prepared for playback (onPlayerReady) and when the video changes its status — for example, when the playback ends (onPlayerStateChange):
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
if (event.data === 0) {
//video finalizado
}
}It is activated on key player events:
- State Meaning
- -1 unstarted
- 0 ended
- 1 playing
- 2 paused
- 3 buffering
- 5 video cued
How to react when a video ends (state 0)
When the video ends, we usually load another one:
function onPlayerStateChange(event) {
if (event.data === 0) {
event.target.loadVideoById({
videoId: siguienteVideoId,
});
}
}Playing a new video when a YouTube video finishes playing
We will also need to include the event that will indicate to us every time there is a change in the video. In our case, we are interested in knowing when the playback of a video has finished to load another one using the loadVideoById method, which receives the identifier of a YouTube video:
function onPlayerStateChange(event) {
if (event.data === 0) {
event.target.loadVideoById({
videoId: $($('.lista_canciones li')[index]).attr("data-href")
});
}
}With this, we have the basic elements to create our own automated and custom playlist from our website; you can consult the official documentation at the following link: YouTube Player API Reference for iframe Embeds.
Play, pause, change volume, and skip video
player.playVideo();
player.pauseVideo();
player.seekTo(30);
player.setVolume(50);
player.stopVideo();Essential methods of YT.Player:
- playVideo() → start
- pauseVideo() → pause
- seekTo(seconds) → skip
- loadVideoById(id) → change video on the fly
- cueVideoById(id) → load without playing
- getPlayerState() → check the state
Advanced player options (playerVars)
YouTube offers an arsenal of parameters:
- autoplay
- controls
- start / end
- rel
- modestbranding
- playsinline
- playlist
- loop
- color (white/red)
- cc_load_policy
Example:
playerVars: {
autoplay: 1,
controls: 2,
modestbranding: 1,
rel: 0,
playsinline: 1,
}Common uses
- Automate playback
- When developing a song list, I needed the next one to start when one finished. The API solved this with event.data === 0.
- Load videos based on user selection
- I managed to change the video without reloading the page when clicking a DOM element using loadVideoById.
- Improve the UX
- The player notified me when the video was ready (onReady), so I adjusted the UI to show a "loading" animation.
Frequently Asked Questions (FAQ)
- Do I need to know a lot of JavaScript?
- No. You'll manage well with basic functions and callbacks.
- The IFrame API controls the player.
- The Data API handles data (searches, lists, uploading videos...).
- Can I completely avoid related videos?
- Not 100%, but rel=0 improves the behavior.
Conclusion
The YouTube IFrame Player API is a very powerful tool for any site that needs to manage videos beyond the typical static iframe; I use it with my Academy app for the courses I load from YouTube.
With it, you can:
- Create dynamic players
- Detect states
- Automate playlists
- Improve the UX
- Integrate videos professionally
If you already have your own UI structure or lists, this API will allow you to unite everything with a flexible and controllable player.
I agree to receive announcements of interest about this Blog.
Learn to master the YouTube iFrame Player API with this comprehensive guide. Control playback, create automatic playlists, and customize your videos with JavaScript.