By using this site you agree to the use of cookies.

Learn more

Change Iframe src with JavaScript

Cool tutorial on how to change the iframe src attribute value using JavaScript.

Edited: 2017-02-02 19:25

In this tutorial, you can learn how to dynamically change the src attribute of a HTML iframe using DHTML (JavaScript).

we will be using a select drop down menu, and a button element to activate the function that will change the src attribute.

The below is a fully working example. You can copy and paste it into a .html file on your computer, and open it in your browser. The JavaScript itself is explained in the subsections of this article.

<!DOCTYPE html>
<html>

  <head>
    <title>Change src value of iframe dynamically</title>
    <script type="text/javascript">
     function newSrc() {
      var e = document.getElementById("MySelectMenu");
      var newSrc = e.options[e.selectedIndex].value;
      document.getElementById("MyFrame").src=newSrc;
     }
    </script>
    <style type="text/css">
      select {clear:both;}
    </style>
  </head>

  <body>
    <iframe src="https://beamtic.com/" style="width:450px;height:450px;overflow:scroll;" id="MyFrame"></iframe>
    <select id="MySelectMenu">
     <option value="http://yahoo.com/">Yahoo</option>
     <option value="http://www.google.com/custom">Google</option>
     <option value="https://beamtic.com/">Beamtic</option>
    </select>
    <button onClick="newSrc();">Change Iframe Src</button>

  </body>

</html>

Creating the Select Drop Down

The select menu consists of the select element, and multiple option elements, one for each site you want to allow in the iframe. I.e.

<select id="MySelectMenu">
  <option value="http://yahoo.com/">Yahoo</option>
  <option value="http://www.google.com/custom">Google</option>
  <option value="https://beamtic.com/">Beamtic</option>
</select>

You should place this somewhere in the body of your HTML – it does not really matter where you place it, as long as its in the body.

You can now select the different options from the drop down, but before it will work, you will also need a means of getting the value of the selected option. For this we will be making a custom JavaScript function that can be called via the onClick event on a button. Therefor, you should create a button element somewhere. I.e.

<button onClick="newSrc();">Change Iframe Src</button>

The JavaScript Code

The custom function that we will be using is really simple, it only has 3 lines of code!

function newSrc() {
  var e = document.getElementById("MySelectMenu");
  var newSrc = e.options[e.selectedIndex].value;
  document.getElementById("MyFrame").src=newSrc;
}

The first line will create a reference to the select element that we will be using, for simplicity we doing it by ID in this tutorial.

The second line fetches the value of the currently selected option element, which will then be handed over to the iframe in the final and third line of code.