0

I have multiple YouTube iframes embedded on one page. I want when one video starts playing, all other videos should get stopped/paused.

I found a similar question where the user does it for 2 embedded iframes on 1 page using the iframe API. Now my iframes are created dynamically and there are more that 2 iframes on a page.

I am already using the iframe API to track GA events. Following is my code for that

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

function onYouTubeIframeAPIReady(event) {
  player = new YT.Player('ytplayer', {
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
}

var pauseFlag = false;
function onPlayerReady(event) {
}
function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING) {
        ga('send', 'event', 'Youtube', 'Play', player.getVideoData().title);
        pauseFlag = true;
    }
    if (event.data == YT.PlayerState.PAUSED && pauseFlag) {
        ga('send', 'event', 'Youtube', 'Pause', player.getVideoData().title);
        pauseFlag = false;
    }
    if (event.data == YT.PlayerState.ENDED) {
        ga('send', 'event', 'Youtube', 'Finished', player.getVideoData().title);
    }
}

How can I stop/pause any other video playing using the onPlayStateChange() function?

Community
  • 1
  • 1
Yin Yang
  • 1,776
  • 3
  • 26
  • 48

1 Answers1

-1

You can access the specific Player and stop them.

var myPlayer = document.getElementById('playerid');
    myPlayer.stopVideo();
AngularLover
  • 364
  • 1
  • 12