YouTube Player API for iframe Embeds
Docs: https://developers.google.com/youtube/iframe_api_reference
The HTML (src with enablejsapi=1
param):
<iframe id="existing-iframe-example"
src="https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1"
></iframe>
1 of 4 - Load iframe API
// 1. Loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
2 of 4 - onYouTubeIframeAPIReady function
Any web page that uses the IFrame API must also implement the following JavaScript function onYouTubeIframeAPIReady
.
function onYouTubeIframeAPIReady() {
/* execute as soon as the player API code downloads */
console.log("Youtube API is ready);
}
3 of 4 - Create YT.Player object (Select the iframe by videoId)
/* Player */
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('existing-iframe-example');
}
Related: How can I use a class instead of id for new YT.Player()
4 of 4 - Use Youtube Iframe API methods:
player.stopVideo();
// player.playVideo()
// player.pauseVideo()
Click Events Part
With this in mind stop the video on any logic:
JS
/* Stop Video on click */
const stop_button = document.querySelector('[stop]');
stop_button.addEventListener("click", () => {
player.stopVideo();
})
jquery on()
/* Stop Video on click */
$( "[stop]" ).on( "click", function() {
player.stopVideo();
});
Code snippet
**No way to load youtube iframe inside stackoverflow snippet (codepen demo)
/* load Youtube Iframe API */
var tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
/* Player */
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('existing-iframe-example');
}
/* Stop Video on click */
const stop_button = document.querySelector('[stop]');
stop_button.addEventListener("click", () => {
player.stopVideo();
})
<button stop>Stop Video</button><br>
<iframe id="existing-iframe-example"
width="640" height="360"
src="https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1"
frameborder="0"
style="border: solid 4px #37474F"
></iframe>