How to remove an element and replace a second one on click in JavaScript?

1k views Asked by At

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?

2

There are 2 answers

0
a.mola On

You can use the replaceWith method

elementToBeReplaced.replaceWith(elementToReplaceWith);

Or you can insertBefore the elementToBeReplaced then remove() it.

elementToBeReplaced.parentElement.insertBefore(elementToReplaceWith, elementToBeReplaced);
elementToBeReplaced.remove();
0
Ayman Jabr On

There are 2 ways I would do this, and they both boil down to giving the div that you want to hide a display = none property, you could just straight up get the elements in a variable and then change their display property as shown here.

Or add a special class in your CSS file, with just display = none given to it, and add that class to the div that you don't want to show, this example shows how to toggle the class on and off.