Change YouTube embed iframe video in JavaScript

By Faruque Ahamed Mollick

Lots of us know that anyone can get the embed code from YouTube for a video. This code is nothing but simple HTML iframe tag having the YouTube video path in the src attribute. All we need to do is just paste this code on our web page and it will then start showing the video on that page.

We can easily get the YouTube video embed code just by clicking on share option of the YouTube video page to get the embed code of that video.

Now in this post, I am going to show you how to change YouTube embed iframe video in JavaScript with the simple and easy code snippet.



Here I am going to show you step by step.

At first, let add our YouTube embed iframe video HTML code on our web page:

<iframe id="ytVideo" width="560" height="315" src="https://www.youtube.com/embed/eDkpVwrhYfo" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

We have given our iframe an ID. By using this ID, we are going to change our video in javaScript.

HTML DOM already has an iframe src property. With this property, we can set a new URL or src for our iframe video. To change YouTube embed iframe video, we just need to change the src attribute value of the iframe with the new YouTube video embed URL using javaScript iframe src property.

 

Also, read:

 

Below is our javaScript code to set a new iframe src URL to change YouTube iframe video:

document.getElementById('ytVideo').src = "https://www.youtube.com/embed/bo2KQer1KNM";

The above line of JavaScript code will change our embedded YouTube video of the iframe.

Now suppose, we want to change our video by clicking a button. So we have to apply the click event listener like you can see below:

 
document.getElementById("change-video").onclick = function() {
   document.getElementById('ytVideo').src = "https://www.youtube.com/embed/bo2KQer1KNM";
};

 

In the above code, “change-video” is our button ID. Clicking this button will change YouTube iframe video content.

Complete code to change YouTube iframe video content on clicking button

Now below is our complete code:

<iframe id="ytVideo" width="560" height="315" src="https://www.youtube.com/embed/eDkpVwrhYfo" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

<br>
<button id="change-video">Change Video</button>


<script type="text/javascript">
  
document.getElementById("change-video").onclick = function() {
    document.getElementById('ytVideo').src = "https://www.youtube.com/embed/bo2KQer1KNM";
};

</script>

Now you can run this code on your browser and you can check it by clicking the button. You can see that when you click the button, it remove the old video and add a new one.

So we did it successfully.

 

Leave a Reply

Your email address will not be published. Required fields are marked *