You don’t really need that setInterval
trick. If you just want the video to play normally with pause support, you can keep the default YouTube controls instead of hiding them. Just remove ?controls=0
from the src
and also remove the opacity:0;
style, and remove the custom play button:
<iframe width="560" height="315"
src="https://www.youtube.com/embed/Gu2PVTTbGuY"
frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
style="position:absolute; top:0; left:0;"
id="player">
</iframe>
That way YouTube gives you play, pause, and volume controls out of the box on all browsers and devices.
If you do want a custom play button overlay, you can still do it with a simple toggle:
<div style="position: relative; width:560px; height:315px;">
<img src="http://s3.amazonaws.com/content.newsok.com/newsok/images/mobile/play_button.png"
style="position:absolute;top:0;left:0;cursor:pointer;" 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;" id="player">
</iframe>
</div>
<script>
window.addEventListener('DOMContentLoaded', () => {
const cover = document.getElementById('cover');
const player = document.getElementById('player');
// Show cover initially
cover.style.zIndex = '2';
player.style.opacity = '0';
cover.addEventListener('click', () => {
cover.style.display = 'none'; // hide overlay
player.style.opacity = '1'; // show player
// user will then click the YouTube play/pause buttons
});
});
</script>
This way the video only appears once the user clicks your custom image. From that point, YouTube’s own play/pause controls take over.
👉 If you want the video to actually start playing when your custom button is clicked, without the user pressing the YouTube play button, you’ll need to use the YouTube Iframe API. That’s the only way to programmatically call player.playVideo()
or player.pauseVideo()
with your own custom buttons.