0

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 ?

Community
  • 1
  • 1
Bogdan Bogdanov
  • 882
  • 11
  • 36
  • 79

1 Answers1

3

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

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • @BogdanBogdanov - Then you're doing something else wrong, as this works just fine -> **http://jsfiddle.net/Q7nbq/** – adeneo May 01 '14 at 12:17