I found this code that allows me to play a YouYube video when I click a custom play button:
<div style="position: relative;">
<img src="http://s3.amazonaws.com/content.newsok.com/newsok/images/mobile/play_button.png" style="position:absolute;top:0;left:0;opacity:1;" id="cover">
<iframe width="560" height="315" src="https://www.youtube.com/embed/Gu2PVTTbGuY?controls=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen style="position: absolute;top:0;left:0;opacity:0;" id="player"></iframe>
</div>
<script>
setInterval(function(){
if(document.activeElement instanceof HTMLIFrameElement){
document.getElementById('cover').style.opacity=0;
document.getElementById('player').style.opacity=0;
}
} , 50);
</script>
Originally, the player had an opacity=1, but I actually just want to play the audio from the video instead of showing the actual video so this works quite nicely.
The one thing I'd like for it to have is a pause.
Right now, you click the "play" image and the video doesn't show, but plays audio. Any way for a "pause" image to show where the play button used to be so the audio can stop playing if the user decides they don't want it to play anymore?
I am also open to use some other code, this is the only thing I've been able to find that is cross-browser compliant, that's actually capable of doing what I want it to do on both desktop and mobile.
Thanks,
Josh
This is what ultimately got me going:
<div style="position: relative; width: 560px; height: 315px;">
<div id="cover" style="position:absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); opacity:1; cursor:pointer; font-size:100px; color:white; text-shadow: 2px 2px 4px #000000;">
<i class="fas fa-play"></i>
</div>
<iframe id="player" width="560" height="315" src="https://www.youtube.com/embed/2qhCjgMKoN4?enablejsapi=1&controls=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen style="position: absolute; top:0; left:0; opacity:0;"></iframe>
</div>
<script src="https://www.youtube.com/iframe_api"></script>
<script>
var player;
var playButton = document.getElementById('cover');
var icon = playButton.querySelector('i');
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
playButton.addEventListener('click', function() {
if (player.getPlayerState() == YT.PlayerState.PLAYING) {
player.pauseVideo();
} else {
player.playVideo();
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
icon.classList.remove('fa-play');
icon.classList.add('fa-pause');
} else {
icon.classList.remove('fa-pause');
icon.classList.add('fa-play');
}
}
</script>
Thanks,
Josh