Sometimes, we want to control an iframe player that’s already in the HTML with JavaScript.
In this article, we’ll look at how to control an iframe player that’s already in the HTML with JavaScript.
How to control an iframe player that’s already in the HTML with JavaScript?
To control an iframe player that’s already in the HTML with JavaScript, we can specify the ID of the iframe in the YT.Player
constructor.
For instance, we write
<iframe
id="player"
src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&origin=http://example.com"
frameborder="0"
></iframe>
to add the YouTube video iframe.
Then we write
let player;
const onPlayerStateChange = () => {
//...
};
const onYouTubeIframeAPIReady = () => {
player = new YT.Player("player", {
events: {
onStateChange: onPlayerStateChange,
},
});
};
to create the YT.Player
object with the ID of the iframe as the first argument.
Conclusion
To control an iframe player that’s already in the HTML with JavaScript, we can specify the ID of the iframe in the YT.Player
constructor.