JSFiddle - React, Tailwind, and code Playground

by icodeforlove

HTML

<script src="https://www.youtube.com/player_api"></script>
<iframe class="player" width="560" height="315" src="//www.youtube.com/embed/nbp3Ra3Yp74" frameborder="0" allowfullscreen></iframe>
<iframe class="player" width="300" height="300" src="//www.youtube.com/embed/cMGlavA8LX8" frameborder="0" allowfullscreen></iframe>
<iframe class="player" width="560" height="315" src="//www.youtube.com/embed/nbp3Ra3Yp74" frameborder="0" allowfullscreen></iframe>

JavaScript

var youtubeRegExp = /www.youtube.com\/embed\/([a-z0-9]+)/i,
    states = ['unstarted', 'ended', 'playing', 'paused', 'buffering', 'video cued'];

Array.prototype.slice.call(document.querySelectorAll('iframe')).filter(function (element) {
    return youtubeRegExp.test(element.src);
}).forEach(swapVideo);

function swapVideo (target) {
    var container = document.createElement('div');
    
    target.parentNode.replaceChild(container, target);

    var player = new YT.Player(container, {
        height: target.height,
        width: target.width,
        videoId: target.src.match(youtubeRegExp)[1]
    });
    
    player.addEventListener('onStateChange', function (event) {console.log(states[event.data+1]); });  
}