Shaoz
Shaoz

Reputation: 10653

changing url of iframe every 20 sec not working with javascript

I have an iframe that I wanna update every 20 seconds. So basically, the url of the iframe should change to a new one from the array and it refreshes, every 20 seconds but my code doesn't seem to work.

var Uni = {
    init: function () {
        this.refresh();
    },

    refresh: function () {
        var urlArr = [
            'http://www.smashingmagazine.com/learning-javascript-essentials-guidelines-tutorials/',
            'http://stephendnicholas.com/archives/310',
            'http://msdn.microsoft.com/en-us/scriptjunkie/ff696765', 
            'http://www.jquery4u.com/jquery-functions/jquery-each-examples/'
        ],

        iframeSrc = document.querySelector('#uni iframe').src;

        for (var i = 0, max = urlArr.length; i < max; i++) {
            setInterval(function(){
                iframeSrc = urlArr[i];
            }, 20000);
        }   
    }
}

Uni.init();

HTML:

<body id="uni">
   <iframe src="http://www.smashingmagazine.com/learning-javascript-essentials-guidelines-tutorials/">
   You browser doesn't support iframes, please update it.
   </iframe>
</body>

Please help.

Upvotes: 2

Views: 650

Answers (2)

vzwick
vzwick

Reputation: 11044

Check the last line of your urlArr[] declaration:

], // <- the comma should be a semicolon!

Thanks to @AndyE for the hint.

Update: Solution + working fiddle

var Uni = {
    interval_holder : false,
    urlArr : [],

    init: function (args) {
        if (args) {
            for (url in args) { this.addUrl(args[url]); }
        };
        this.refresh();
        this.interval_holder = setInterval('myuni.refresh()', 20000);
        return this;
    },

    refresh: function () {
        iframeObj = document.querySelector('#uni iframe');
        this.urlArr.unshift(iframeObj.src);
        iframeObj.src = this.urlArr.pop();
        return this;
    },

    stop : function () {
        clearInterval(this.interval_holder);
        return this;
    },

    addUrl : function(url) {
        this.urlArr.push(url);
        return this;
    },

    removeUrl : function(url) {
        this.urlArr.splice(this.urlArr.indexOf(url),1);
        return this;
    }
};

window.myuni = Uni.init([
    'http://www.smashingmagazine.com/learning-javascript-essentials-guidelines-tutorials/',
    'http://stephendnicholas.com/archives/310',
    'http://msdn.microsoft.com/en-us/scriptjunkie/ff696765', 
    'http://www.jquery4u.com/jquery-functions/jquery-each-examples/'
]);

Upvotes: 3

Shadow Wizard
Shadow Wizard

Reputation: 66388

The iframe src attribute is only a string, not pointer. Changing it has no effect.

Have this instead:

iframeObj = document.querySelector('#uni iframe');
for (var i = 0, max = urlArr.length; i < max; i++) {
    setInterval(function(){
        iframeObj.src = urlArr[i];
    }, 20000);
}

Upvotes: 2

Related Questions