JSFiddle - React, Tailwind, and code Playground
by Kai
HTML
<div id="video-container"></div>
JavaScript
function ytVideo(videoId, container) {
var src = 'http://www.youtube.com/embed/' + videoId + '?autoplay=1&controls=0'; // autoplay, hide controls
// We only need to change the src of the existing iframe
// element if it's cached
if (ytVideo.el) {
ytVideo.el.setAttribute('src', src);
return;
}
// 'container' can be an ID or an element itself
if (typeof container === 'string') {
container = document.getElementById(container);
}
var iframe = ytVideo.el = document.createElement('iframe');
iframe.setAttribute('width', 577);
iframe.setAttribute('height', 359);
iframe.setAttribute('frameborder', 0);
iframe.setAttribute('class', 'youtube-player');
iframe.setAttribute('src', src);
container.appendChild(iframe);
}
// Play some video
ytVideo('_Q37IuFMtAQ', 'video-container');
// Play another 7 seconds later... (video-container is cached after first use)
setTimeout(function() {
ytVideo('dQw4w9WgXcQ');
}, 7000);