How do I dynamically change the content in an iframe using jquery?

JqueryIframe

Jquery Problem Overview


I was wondering if it is possible to have a site with an iframe and some jquery code that changes the iframe content every 30 seconds. The content is in different webpages.

Something like this:

<html>
  <head>
    <script type="text/javascript" src="jquery.js"></script>
    <script>
      $(document).ready(function(){
        var array = new array();
        array[0] = 'http://webPage1.com';
        array[1] = 'http://webPage2.com';
        // And so on.
        // Do something here to change the iframe every 30 second
      });
    </script>
  </head>
  <body>
    <iframe id="frame"></iframe>
  </body>
</html>

Jquery Solutions


Solution 1 - Jquery

<html>
  <head>
	<script type="text/javascript" src="jquery.js"></script>
	<script>
	  $(document).ready(function(){
		var locations = ["http://webPage1.com", "http://webPage2.com"];
		var len = locations.length;
		var iframe = $('#frame');
		var i = 0;
		setInterval(function () {
			iframe.attr('src', locations[++i % len]);
		}, 30000);
	  });
	</script>
  </head>
  <body>
	<iframe id="frame"></iframe>
  </body>
</html>

Solution 2 - Jquery

If you just want to change where the iframe points to and not the actual content inside the iframe, you would just need to change the src attribute.

 $("#myiframe").attr("src", "newwebpage.html");

Solution 3 - Jquery

var handle = setInterval(changeIframe, 30000);
var sites = ["google.com", "yahoo.com"];
var index = 0;

function changeIframe() {
  $('#frame')[0].src = sites[index++];
  index = index >= sites.length ? 0 : index;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAudunView Question on Stackoverflow
Solution 1 - JqueryAnatoliyView Answer on Stackoverflow
Solution 2 - JqueryAnthonyView Answer on Stackoverflow
Solution 3 - Jquerygeowa4View Answer on Stackoverflow