JSFiddle - React, Tailwind, and code Playground
by oilvier
HTML
<div data-video="background">
<div class="foo" data-id="ScMzIvxBSi4" data-params='{"iv_load_policy": 3, "enablejsapi": 1, "autoplay": 1, "modestbranding": 1, "rel": 0, "loop": 0, "controls": 0, "playsinline": 1, "origin": "window.location.href"}' data-autoplay="true"></div>
</div>
CSS
[data-video="background"] {
pointer-events: none;
}
JavaScript
$( document ).ready(function() {
console.log('ok');
if ($('[data-video=container]').length || $('[data-video=background]').length) {
if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') {
// Create script tag to Load the iFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
// Add the script tag to the page
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
// Create variables needed for the iFrame players
var everyIframePlayers = new Array(),
iframePlayer;
function initPlayer(element) {
var thisVideoCover = element,
thisVideoPlaceholder = thisVideoCover.find('[data-params]'), // `div` tag that will be replaced with our iframe
thisVideoId = thisVideoPlaceholder.data('id'), // get the YouTube video ID
thisVideoParams = thisVideoPlaceholder.data('params'), // get the params for the player
thisVideoAutoplay = thisVideoPlaceholder.data('autoplay'); // get the autoplay preference
iframePlayer = new YT.Player(thisVideoPlaceholder[0], {
height: '360',
width: '640',
host: 'https://www.youtube-nocookie.com', // Force the use of cookieless YouTube
videoId: thisVideoId,
playerVars: thisVideoParams,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
everyIframePlayers.push(iframePlayer); // store all players in the same array
// When the player is ready:
// 1. Remove class indicating the video loading
// 2. Add class to replace image...