Youtube Iframe API

Controlling youtube iframes, e.g. Pausing or resetting video on events like carousel slide change, popup close/open, etc.

https://developers.google.com/youtube/iframe_api_reference

1.) Load Youtube Iframe API js

				
					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();
				
			

2.) Attach Youtube Player instance to each iframe element

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);
    })
}
				
			

3.) On an event, play, stop, pause the player

Playback Controls:

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();
        });
    }
});
				
			

Share This

Select your desired option below to share a direct link to this page.
Your friends or family will thank you later.