JSFiddle - React, Tailwind, and code Playground
by Chris LaFrombois
HTML
<script src="https://www.youtube.com/iframe_api"></script>
<div class="wrapper">
<div class="overlay">
<a href="#" class="overlay-button" data-target="iframe-1000">
Click me to play
</a>
</div>
<iframe class="video-iframe" id="iframe-1000" width="600" height="480" frameborder="0" title="YouTube video player" type="text/html" src="http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe>
</div>
<div class="wrapper">
<div class="overlay">
<a href="#" class="overlay-button" data-target="iframe-1001">
Click me to play
</a>
</div>
<iframe class="video-iframe" id="iframe-1001" width="600" height="480" frameborder="0" title="YouTube video player" type="text/html" src="https://www.youtube.com/embed/TPZtF9xHFR8?enablejsapi=1"></iframe>
</div>
<div class="wrapper">
<div class="overlay">
<a href="#" class="overlay-button" data-target="iframe-1002">
Click me to play
</a>
</div>
<iframe class="video-iframe" id="iframe-1002" width="600" height="480" frameborder="0" title="YouTube video player" type="text/html" src="https://www.youtube.com/embed/_EvMYEfF_hQ?enablejsapi=1"></iframe>
</div>
SCSS
.wrapper {
position: relative;
}
.overlay {
background-image: url(http://placehold.it/800x450);
background-size: cover;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: block;
text-align: center;
a {
display: inline-block;
padding: 20px;
color: #fff;
background: red;
text-decoration: none;
position: relative;
margin: 0 auto;
top: 50%;
transform: translate(0, -50%);
}
}
JavaScript
var ytplayers = [],
players = [];
function onYouTubeIframeAPIReady() {
$("[id^=iframe-]").each(function() {
ytplayers.push($(this).attr("id"));
});
ytplayers.forEach(function(id, i) {
players[id] = new YT.Player(id, {
events: {
'onReady': getTime
}
})
});
}
function getTime(event) {
var vtime = event.target.getDuration(),
frame_id = event.target.a.id;
$('.overlay-button').each(function(){
if( $(this).data('target') == frame_id ) {
$(this).append('<span>' + vtime + '</span>')
}
});
}
$('.overlay-button').on('click', function(e) {
e.preventDefault();
ytplayers.forEach(function(id, i){
players[id].pauseVideo();
});
var p_id = $(this).data('target');
players[p_id].playVideo();
$(this).parent().css('display', 'none');
});