Controlling youtube iframes, e.g. Pausing or resetting video on events like carousel slide change, popup close/open, etc.
function load_youtube_api(){
if( typeof YT !== 'undefined' ) return;
var tag = document.createElement("script");
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
load_youtube_api();
The script above would look for the function onYouTubeIframeAPIReady and run it automatically. We will put our codes in this function to attach the Youtube Player instance for each iframe, which we will use later to control the player.
function onYouTubeIframeAPIReady(){
var iframes = document.querySelectorAll('.selector_here iframe');
if( !iframes ) return;
// assign youtube api player to iframes
iframes.forEach(iframe => {
iframe.yt = new YT.Player(iframe);
})
}
player.playVideo()
player.pauseVideo()
player.stopVideo()
for example on slick change, stop videos that are playing
document.addEventListener('DOMContentLoaded', () => {
var slider = jQuery('.selector_here');
slider.slick();
slider.on('beforeChange', function(){
stop_youtube_videos(slider);
});
function stop_youtube_videos(el){
el.find('.slick-active iframe').each(function(){
if( typeof this.yt === 'undefined' ) return; // check if it has youtube player / assigned on step 1
if( this.yt.getPlayerState() != 1 ) return; // not playing
this.yt.stopVideo();
});
}
});
Select your desired option below to share a direct link to this page.
Your friends or family will thank you later.