Search code examples
arraysrefreshcycle

change/cycle through text on page refresh


I have a div whose text updates randomly on page refresh, but what I need is for the text to cycle through in the order its listed instead of at random each time the page reloads.

var myFact = new Array();
    myFact[0] = "I have a dog";
    myFact[1] = "My favorite sport is hockey";
    myFact[2] = "I like chocolate";
    myFact[3] = "Orange is my favorite color";
var myRandom = Math.floor(Math.random()*myFact.length);
document.getElementById('myFact').innerHTML= myFact[myRandom];

(since this is seemingly such an easy request and I fear I'll be eaten alive on here I will follow up with: yes, I have googled it but cannot find an answer that makes sense to my non-js-proficient brain. there is lots of how to cycle through on click OR update randomly on page refresh… but not how to cycle through on page refresh)

http://jsfiddle.net/pixeloco/Ma2VA/


Solution

  • You can accomplish this using localStorage. which is session based. (meaning it wont go away till the browser is closed).

    you can use the localStorage object as a bucket to put vars you want to retain after refresh.

    <div id="myFact"></div>
    <script>
    if (typeof(Storage) !== undefined) {
        var myFact = new Array();
        myFact[0] = "I have a dog";
        myFact[1] = "My favorite sport is hockey";
        myFact[2] = "I like chocolate";
        myFact[3] = "Orange is my favorite color";
        //var myRandom = Math.floor(Math.random()*myFact.length);
        if (!localStorage.factIndex) {
            localStorage.factIndex = 0;
        } else {
            localStorage.factIndex = (localStorage.factIndex >= (myFact.length-1)) ? 0: parseInt(localStorage.factIndex)+1;
        }
        document.getElementById('myFact').innerHTML = myFact[localStorage.factIndex];
    } else {
        //LocalStorage not supported with this browser
    }
    </script>