1

I have the following JavaScript to rotate pages in a iframe tag every 5 seconds.

function setPage() {
    if (i == pages.length) {
        i = 0;
    }
    alert(pages[i]); //verify the right url is there
    var elmnt = document.getElementById('dashboard');
    elmnt.setAttribute('src', pages[i]);

    i++;
}
setInterval("setPage()", 5000);

The loop, interval, etc., is working. However, nothing changes for the src attribute of my iframe tag.

I tested with both IE8 and Chrome.

What am I doing wrong? How can I accomplish that (no jQuery...)

Amarundo
  • 2,357
  • 15
  • 50
  • 68

3 Answers3

2

I'd suggest you to use elmnt.src = pages[i] instead.

If it still gives you error, then most probably you are trying to target element, that doesn't have src property. Check that elemt.tagName gives you IFRAME.

VisioN
  • 143,310
  • 32
  • 282
  • 281
1

Have you tried just manually setting the src property of the iframe?

document.getElementById('dashboard').src = pages[i];
Paul Gleeson
  • 438
  • 4
  • 10
1

As you have it now, each time setPage gets called, the value i is undefined; if you want the value of i to be held from call to call, you need to set it in a closure:

var setPage = (function () {
    var i = 0;
    return function () {
        if (i == pages.length) {
            i = 0;
        }
        var elmnt = document.getElementById('dashboard');
        elmnt.setAttribute('src', pages[i]);
        i++;
    }
}());

Also when setting the interval, the first argument should just be the name of the function, no quotes or parens:

setInterval(setPage, 5000);

There's a couple other tweaks you could make to it, but that should get it running.

Community
  • 1
  • 1
ultranaut
  • 2,132
  • 1
  • 17
  • 22
  • The counting logic is correct. I `alert` the value of `pages[i]` and it's giving me the right value. `i` is set to `0` only when `i` reaches the length of the array. – Amarundo Mar 22 '13 at 16:14
  • You sure? Just using what you have above, `i` is going to be `undefined` each time `setPage` is called. – ultranaut Mar 22 '13 at 16:30
  • Yes. I works. Not all the code is here, though. `i=0` is before the function, after the ` – Amarundo Mar 22 '13 at 17:24