Question

I use code from HERE (Stackoverflow.com)

I do it for my stuff like this

var i = 0;
var links = ["http://www.example.com/page","http://www.example.com/anotherpage"];
var renew = setInterval(function(){
    document.getElementById("changelink").href = links[i];        
    if(links.length==i){
        i=0;
    }else{
        i++;
    }
},5000);
<a id='changelink' href='http://google.bg/'>test</a>

but when the link change it writes me undefined, I try with the same code with iframe and also gives me undefined whats going on ?

Was it helpful?

Solution

Your count is off by one

var i = 0;
var links = ["http://www.example.com/page", "http://www.example.com/anotherpage"];
var renew = setInterval(function () {
    document.getElementById("changelink").href = links[i];
    if (links.length - 1 == i) {
        i = 0;
    } else {
        i++;
    }
}, 5000);

When links.length == i you're actually trying to get an array index that doesn't exists, so you'll have to subtract one and do links.length - 1 == i

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top