I can't quite figure out how to make the YouTube API play fair when it comes to multiple videos on one page.
I want to show a placeholder image in place of an iframe, then have the actual iframe load in and autoplay when the placeholder is clicked.
I have created a Codepen example. It works for one video, but with multiple videos, you have to click the last video in the sequence and work your way back. If you click the first video, then the second, for example, the second does not load properly.
https://codepen.io/ssmyth93/pen/MWELMJw
Here is the JS:
var config = { modestbranding: 1, rel: 0, showinfo: 0, controls: 1, disablekb: 1, enablejsapi: 0, iv_load_policy: 3};var youtube = document.querySelectorAll(".youtube--wrapper");if (youtube) { function loadPlayer() { var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); } document.addEventListener("load", loadPlayer()) var count = 0; for (var i = 0; i < youtube.length; i++) { var source = "https://img.youtube.com/vi/"+ youtube[i].dataset.embed +"/sddefault.jpg"; var image = new Image(); image.src = source; image.addEventListener("load", function () { youtube[i].appendChild(image); }(i)); youtube[i].addEventListener("click", (e) => { e.currentTarget.innerHTML = '<div id="player'+ count +'"></div>'; new YT.Player('player'+ count, { videoId: e.currentTarget.dataset.embed, events: {'onReady': function (event) { event.target.playVideo(); } }, playerVars: config }); }); count++; }}
Thanks!