Andrew Pomorski Andrew Pomorski - 1 month ago 7
HTML Question

iterating array on refresh

How could I go about writing a snippet, that could iterate through array on refresh?
Say I have an array with banner links, and I'd like the banner to change to next one when refreshed. There is a lot of solutions to make it random, but I want it to loop through array in order, and go to the first one after last.

var banner = new Array();
banner[0] = "http://placehold.it/728x90?text=one";
banner[1] = "http://placehold.it/728x90?text=two";
banner[2] = "http://placehold.it/728x90?text=three";
banner[3] = "http://placehold.it/728x90?text=four";

for(var i=0; i < banner.length; i++){
var img = document.getElementById("imageid");
img.src = banner[i];
}


This is the code that I currently have, but it's obviously not working.

Thank you in advance

Answer

Use localStorage like so:

var banner = new Array();
banner[0] = "http://placehold.it/728x90?text=one";
banner[1] = "http://placehold.it/728x90?text=two";
banner[2] = "http://placehold.it/728x90?text=three";
banner[3] = "http://placehold.it/728x90?text=four";    

if (!localStorage.i || localStorage.i == 3) localStorage.i = 0;
else localStorage.i++;

var img = document.getElementById("imageid");
img.src = banner[localStorage.i];

Explanation: At first page load, localStorage.i will be 0. When you refresh, the value increases by 1 only until 3, then back to 0 afterwards.

Comments