Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotating URLs within an Iframe

Tags:

javascript

I have 10 different urls that I want to feed into an iframe src attribute that I would also like to rotate say every 5 seconds between all the 10 urls within the iframe.

Unsure how to do this using javascript/best approach?

Sorry, should've mentioned that I am using IE6.

Thanks.

like image 638
tonyf Avatar asked Jun 29 '10 02:06

tonyf


2 Answers

<iframe id="rotator" src="http://...first"></iframe>

<script>
// start when the page is loaded
window.onload = function() {

  var urls = [
    "http://...first",
    "http://...second",
    // ....
    "http://...tenth" // no ,!!
  ];

  var index = 1;
  var el = document.getElementById("rotator");

  setTimeout(function rotate() {

    if ( index === urls.length ) {
      index = 0;
    }

    el.src = urls[index];
    index  = index + 1;

    // continue rotating iframes
    setTimeout(rotate, 5000);

  }, 5000); // 5000ms = 5s
};
</script>
like image 103
25 revs, 4 users 83% Avatar answered Nov 07 '22 22:11

25 revs, 4 users 83%


Javascript (place in window.onload)

var urls = ['http://www.stackoverflow.com', 'http://www.google.com'];
var pos = 0;

next();

setInterval(next, 5000); // every 5 seconds

function next()
{
  if(pos == urls.length) pos = 0; // reset the counter
  document.getElementById('rotate').src = urls[pos];
  pos++;
}

HTML

<iframe id="rotate"></iframe>
like image 33
Ben Rowe Avatar answered Nov 07 '22 21:11

Ben Rowe