Search code examples
javascriptjqueryiframeyoutubeyoutube-api

How do you make multiple Youtube iframe embeds pause on click?


I've got multiple Youtube embeds set up like a playlist, with thumbnail images (class="vid-image") for each video.

I'm wanting any video that is playing to pause when you click on any thumbnail image .

I've found some code, but it's only working for the first video. To see what I mean, play the first video and then click on any of the black boxes (.vid-image) and the video will pause.

But, play either the second or the third video and then click on any of the black boxes, you'll see the video doesn't pause.

I've got a JSFiddle set up here: https://jsfiddle.net/74skr0qt/ but code is also below:

HTML:

<iframe class="youtube-video" width="100%" height="100%" src="https://www.youtube.com/embed/ScMzIvxBSi4?enablejsapi=1&version=3&playerapiid=ytplayer" modestbranding="0"  controls="0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

<iframe class="youtube-video" width="100%" height="100%" src="https://www.youtube.com/embed/NpEaa2P7qZI?enablejsapi=1&version=3&playerapiid=ytplayer" modestbranding="0"  controls="0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

<iframe class="youtube-video" width="100%" height="100%" src="https://www.youtube.com/embed/R5jIoLnL_nE?enablejsapi=1&version=3&playerapiid=ytplayer" modestbranding="0"  controls="0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

<div class="vid-image"></div>
<div class="vid-image"></div>
<div class="vid-image"></div>

JAVASCRIPT:

$('.vid-image').click(function(){
  $('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*');
});

Any help would be much appreciated - I've spent hours trying different solutions with no luck. I'm a beginner at Javascript so unable to figure out how to adjust the code.

Thank you in advance :).


Solution

  • You can achieve this by changing your js to:

    function stopAllVideos() {
      $('.youtube-video').each((i, videoElem) => {
        videoElem.contentWindow.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*');
      });
    };
    
    $('.vid-image').click(stopAllVideos);
    

    You are now posting the message only for the first video, in your code

    $('.youtube-video')[0]
    

    means the video with index 0.

    I changed it to post the pause message for each video element with youtube-video class name