Make youtube iframe api work in tabs / carousel on show

Make youtube iframe api work in tabs / carousel on show

youtube.js

/**
 * My markup for video is generated with PHP and it looks like this:
 *
 * foreach ( $videoURLs as $video_url ) :
 *    
 *   Need to get only video_id param from URL, something like: dEy6mu0UarM
 *
 *   $video_id = explode('=', $video_url);
 *    
 *    
 *   This is div that will be replaced by iframe player.
 *   Note that it needs to have a unique ID so we can find which video to play from list of videos
 *
 *   echo '<div id="video-' . rand(9,999). '" data-video="' . $video_id . '"></div>'
 *
 * endforeach;
 * 
 * Example markup: <div id="video-123" data-video="dEy6mu0UarM"></div>
 *
 */


// First thing's first - include iframe API script
var tag = document.createElement('script');
var firstScriptTag = document.getElementsByTagName('script')[0];

tag.src = "https://www.youtube.com/iframe_api";
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

/**
 * Define variable where I will collect all videos on the page
 */
var videos = new Array;


/**
 * As API suggests this function will be fired on page after API is ready
 * Needs to be on window, otherwise function might not be accessible by YT
 */
window.onYouTubeIframeAPIReady = function() {
    
    // Collect all elements from page that have [data-video] attribute
    const players = document.querySelectorAll(`[data-video]`);
    
    // Loop trough elements
    Array.from(players).forEach(video => {
           
        // Construct new YT player
        const player = new YT.Player(video.id, { // Targeting video by his random id attribute
            height: "360",
            width: "640",
            videoId: video.dataset.video, // Loads video_id from data-video attribute
        });

        // Save our video id in custom property so we can easily find him later
        player.divid = video.id;
        
        // Push YT video object to array for future use
        videos.push( player );
    });
}


/**
 * Now finally to play our video and pause all others
 * video_id = id of iframe element we want to play
 */
function playVideo( video_id = false ) {
    
    /**
     * Loop trough all players in global variable and pause all videos
     */
    videos.forEach( video => {
        video.pauseVideo();
    });
    
    // If there is active video, play
    if ( video_id ) {
        
        // Find index of current video by video_id
        const index = videos.map(e => e.divid).indexOf(video_id);
        
        // Save in video var, just to make it look nice
        const video = videos[index];
        
        // Do your thing here
        video.setVolume(0);
        video.playVideo();
    }
}


/**
 * Now how I used this is in my carousel was eg:
 */
onChange: ( slide ) {
      
    // Check if there is video ifram in my slide and call function to play
    const iframe = slide.querySelector('iframe');
     
    if ( iframe ) {
        playVideo( iframe.id );
    }
}

Jayesh Patel
Author
Jayesh Patel

Jayesh Patel is a Professional Web Developer & Designer and the Founder of InCreativeWeb.

As a highly Creative Web/Graphic/UI Designer - Front End / PHP / WordPress / Shopify Developer, with 14+ years of experience, he also provide complete solution from SEO to Digital Marketing. The passion he has for his work, his dedication, and ability to make quick, decisive decisions set him apart from the rest.

His first priority is to create a website with Complete SEO + Speed Up + WordPress Security Code of standards.



Explore

Related Articles

11th April, 2024

W3 Total Cache: A Comprehensive Review & Guide for 2024

8th April, 2024

Top 10 Must-Have Web Design Resources and Tools for 2024

8th April, 2024

Unleash Accessibility Potential in Front-end Development