YouTube Iframe API - multiple videos (play & pause)
Using the YouTube Iframe API, this jsfiddle play & pause the multiple videos. This is an attempt to answer this question: https://stackoverflow.com/q/54062545/4092887
by MauricioSOes
HTML
<script src="https://s.ytimg.com/yts/jsbin/www-widgetapi-vflkA4wlR/www-widgetapi.js"></script>
<script src="https://www.youtube.com/iframe_api"></script>
<!-- These divs will contain the iframe YouTube player: -->
<div id="player"></div>
<div id="multip"></div>
<a href="#" id="pause">Pause</a>
<a href="#" id="resume">Resume</a>
JavaScript
/*
Sources:
https://developers.google.com/youtube/iframe_api_reference?hl=es-419
https://stackoverflow.com/a/17843719/4092887
https://stackoverflow.com/a/11284045/4092887
https://stackoverflow.com/a/17857716/4092887
https://jsfiddle.net/wzalazar/72NYY/
*/
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Variables of the divs (where the YouTube iframe will load):
var player;
var multip;
function onYouTubeIframeAPIReady() {
// Div player:
player = new YT.Player('player', {
height: '360',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady
}
});
// Div "multip":
multip = new YT.Player('multip', {
height: '360',
width: '640',
videoId: '7gwO8-oqwFw',
events: {
'onReady': onPlayerReady2
}
});
// Add onclick events to HTML anchor controls for play and
// pause the videos.
document.getElementById('resume').onclick = function() {
play_video();
};
document.getElementById('pause').onclick = function() {
pause_video();
};
}
// Div "player" - The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// Div "multip" - The API will call this function when the video player is ready.
function onPlayerReady2(event) {
event.target.playVideo();
}
// Function for play all the loaded iframes: those div are: ("player" and "multip").
function play_video() {
player.playVideo();
multip.playVideo();
}
// Function for pause all the loaded iframes: those div are: ("player" and "multip").
function pause_video() {
player.pauseVideo();
multip.pauseVideo();
}
// Function for reset (start at 0:00) all the loaded iframes: those div are: ("player" and "multip").
function reset_video() {
player.stopVideo();
...