By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Change Iframe src with JavaScript

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

Edited: 2013-08-01 10:59

In this JavaScript Tutorial we will be showing you how to dynamically change the src attribute of an iframe using DHTML. Here we will be using a select drop down menu, and a button element to activate the function that will change the src attribute.

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="http://brugbart.com/">Brugbart</option>
</select>

You should place this somewhere in the body of your HTMLit doesn't 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 for it to actually work, you will need a means of getting the

value of the selected option. For this we will be making a custom javascript function that will be called by the onClick event of a button. Therefor you should also 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.

Example

We saved you the trouble of putting all the code together, below is the complete HTML source for a working page, simply save it to a file.html on your computer, and open it in your browser.

<!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="http://brugbart.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="http://brugbart.com/">Brugbart</option>
    </select>
    <button onClick="newSrc();">Change Iframe Src</button>

  </body>

</html>