I’m trying have more than one YouTube embed video on the page, each of which has it’s own overlay and play button that when clicked hides the relevant overlay and plays video.
I can make it work for a single video, but when I try and add more in and loop over the videos, the onPlayerReady function doesn't seem to be getting called.
https://codepen.io/anon/pen/mqeZgX
Here's my javascript
// Inject YouTube API script
const tag = document.createElement('script');
tag.src = '//www.youtube.com/player_api';
const firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
const players = document.querySelectorAll('.js-video-embed > iframe');
const playButtons = document.querySelectorAll('.video__button');
const overlays = document.querySelectorAll('.video__overlay');
window.onYouTubePlayerAPIReady = () => {
for (var i = 0; i < players.length; i++) {
new YT.Player(players[i], {
events: {
'onReady': onPlayerReady
},
});
}
};
function onPlayerReady() {
for (var i = 0; i < players.length; i++) {
// bind events
playButtons[i].addEventListener('click', () => {
players[i].playVideo();
overlays[i].style.display = 'none';
});
}
}
Thanks in advance for any pointers you may be able to give!