Say I have an array of 3 URLs with an iFrame on the page.
How can I run through these 3 URLs every 5 seconds, and then start over? Ideally the page will stay the same, just the iFrame src will change.
Something like this should work:
setInterval(function(){
var u = 0;
document.getElementById('myiFrame').setAttribute('src',myUrlArray[u]);
if(u < myUrlArray.length-1){
++u;
}else{
u = 0;
}
},5000);
Suppose you have this:
<iframe id="ifr" src="">Your browser does not support iframes</iframe>
You simply need to do this in Javascript:
var URLs = ["url1", "url2", "url3"];
var currURL = 0;
function cycle() {
currURL = (currURL + 1) % 3;
document.getElementById("ifr").src = URLs[currURL];
setTimeout(cycle, 5000);
}
cycle();
The code in the as correct marked answer does not work as it always counts too high. Here is the code which works for me flawlessly:
<html>
<body>
<iframe id="myiFrame" src="a.html" width="100%" height="100%"></iframe>
<script>
var myUrlArray = [
"a.html",
"b.html",
"c.html"
];
var u = 1;
setInterval(function(){
document.getElementById('myiFrame').setAttribute('src',myUrlArray[u]);
u++;
if (u == myUrlArray.length) {u = 0;}
},1000);
</script>
</body>
</html>