Quantcast
Channel: Active questions tagged youtube-api - Stack Overflow
Viewing all articles
Browse latest Browse all 3831

Multiple YouTube embed videos with custom play button

$
0
0

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 scriptconst 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!


Viewing all articles
Browse latest Browse all 3831

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>