async function loadVideo(ids) { let idsArr = ids.split(',') let container = document.querySelector('.site-video-items') for (let id of idsArr) { let data = await fetch(`https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=${id}&format=json`) .then((res) => res.json()) .catch((err) => console.error(err)) let videoBlock = createElementFromTemplate(id, data) container.appendChild(videoBlock) } // Gets the video src from the data-src on each button var $videoSrc; $('.site-video-item').click(function() { $videoSrc = $(this).data( "src" ); console.log($videoSrc) }); // when the modal is opened autoplay it $('#video-modal').on('shown.bs.modal', function (e) { // set the video src to autoplay and not to show related video. Youtube related video is like a box of chocolates... you never know what you're gonna get $("#video").attr('src',$videoSrc + "?autoplay=1&modestbranding=1&showinfo=0" ); }) // stop playing the youtube video when I close the modal $('#video-modal').on('hide.bs.modal', function (e) { // a poor man's stop video $("#video").attr('src',$videoSrc); }) } function createElementFromTemplate(id, item) { const template = document.querySelector('#video-block') const videoBlock = template.content.cloneNode(true) videoBlock.querySelector('.site-video-item').dataset.src = `https://www.youtube.com/embed/${id}` videoBlock.querySelector('.site-video-item').style.order = "-1" videoBlock.querySelector('.site-video-title').innerText = item.title videoBlock.querySelector('.site-video-icon').style.backgroundImage = `url(${item.thumbnail_url})` return videoBlock } $(document).ready(function() { // Gets the video src from the data-src on each button var $videoSrc; $('.site-video-item').click(function() { $videoSrc = $(this).data( "src" ); }); // when the modal is opened autoplay it $('#video-modal').on('shown.bs.modal', function () { // set the video src to autoplay and not to show related video. Youtube related video is like a box of chocolates... you never know what you're gonna get $("#video").attr('src',$videoSrc + "?autoplay=1&modestbranding=1&showinfo=0" ); }) // stop playing the youtube video when I close the modal $('#video-modal').on('hide.bs.modal', function () { // a poor man's stop video $("#video").attr('src',$videoSrc); }) });