I'm trying to create a video player in HTML5 that goes full screen when clicked on play.
I found a very elegant solution:
document.addEventListener('click', function (event) {
// Check if clicked element is a video thumbnail
var videoId = event.target.getAttribute('data-video');
if (!videoId) return;
// Create iframe
var iframe = document.createElement('div');
iframe.innerHTML = '<p>x</p><iframe width="165" height="146" src="https://www.youtube.com/embed/' + videoId + '?rel=0&autoplay=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>';
var video = iframe.childNodes[1];
// Replace the image with the video
event.target.parentNode.replaceChild(video, event.target);
// Enter fullscreen mode
video.requestFullscreen();
}, false);
Where
<div class="wrapper" style="margin-bottom: 20px;border: 1px solid red;margin-right: 11px;">
<p><img data-video="example" alt="Play this video" src="/video/example.jpg" style="width: 164px; height: 114px;"></p>
</div>
Now, when I try adding a play button on it, I did:
<div class="wrapper" style="margin-bottom: 20px;border: 1px solid red;margin-right: 11px;">
<p><img src="/video/example.jpg" style="width: 164px; height: 114px;"></p>
<div class="playpause" id="playButton" data-video="example" alt="Play this video"></div>
</div>
So it grabs the data from the play button. But now, the video thumbnail is not replaced with the video and creates another underneath with the iframe.
How can I, on click, remove the play button and replace the image instead?
You can use the replaceWith method
Or you can insertBefore the elementToBeReplaced then remove() it.