Search code examples
javascriptyoutubeytplayer

Multiple instances of YouTube player inside loop


I have the following code, which works - but the part I can't figure out is how to grab the index in the onReady event. The result is 2,2 instead of 0,1 which I would expect - why?

Codepen

var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var players = [];
var playerEl = document.querySelectorAll('.ytplayer');

 function onYouTubeIframeAPIReady() {
     for (var i = 0; i < playerEl.length; i++) {

         players[i] = new YT.Player(playerEl[i], {
             events: {
                 'onReady': () => { console.log('index: '+i) } // why doesn't this return 0,1 ??
             }
         });
     }
 }
<iframe class="video ytplayer" width="100%" height="390" type="text/html" src="https://www.youtube.com/embed/ScMzIvxBSi4?controls=0&t=31s&loop=1&playlist=ScMzIvxBSi4&showinfo=0&rel=0&enablejsapi=1" frameborder="0" allowfullscreen></iframe>

<iframe class="video ytplayer" width="100%" height="390" type="text/html" src="https://www.youtube.com/embed/iGpuQ0ioPrM?controls=0&t=31s&loop=1&playlist=iGpuQ0ioPrM&showinfo=0&rel=0&enablejsapi=1" frameborder="0" allowfullscreen></iframe>


Solution

  • I managed to solve it using the following code. The mistake I was making was I was trying to store a variable inside an event. The event is async and doesn't know that it's inside a loop - at least I think that's it, please correct me if I'm wrong.

    Codepen working

     function onYouTubeIframeAPIReady() {
         document.querySelectorAll('.ytplayer').forEach((item) => {
             new YT.Player(item, {
                 events: {
                     'onReady': (event) => {
                         event.target.playVideo();
                         event.target.mute();
                     }
                 }
             })
         })
    }