1

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.

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, setInterval would be more appropriate than my solution.
0

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();

1 Comment

use "% URLs.length" instead of "% 3"
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.