JSFiddle - React, Tailwind, and code Playground
by Vladimir
HTML
<script src="https://www.youtube.com/iframe_api"></script>
<!DOCTYPE html>
<html>
<body>
<style type="text/css">
#ytplayer { display: none; }
</style>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<script type="text/javascript" src="https://www.youtube.com/iframe_api"></script>
<div id="ytplayer"></div>
<button>
Play
</button>
<script>
var player;
var ready = false;
var wasStopped = false;
function onYouTubeIframeAPIReady() {
player = new YT.Player('ytplayer', {
height: '360',
width: '640',
videoId: 'dkBLoeWDmE0',
playerVars : {
controls: 0,
rel: 0,
autoplay: 0,
showinfo: 0,
//modestbranding: 1
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
console.log(event.data);
if(event.data == 3 && !wasStopped) {
wasStopped = true;
event.target.pauseVideo();
}
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
ready = true;
event.target.playVideo();
}
document.querySelector('button').addEventListener('click', function() {
if(ready) {
document.querySelector('#ytplayer').style.display = 'block';
player.playVideo();
}
});
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
/*var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
...
CSS
#ytplayer {
/*display: none;*/
}