Question

I've been trying to find an answer to this all morning and can't seem to get it right.

The idea is to have a different array item display when the user clicks the button. The problem is that once they go to a different page, the array resets back to 0 and starts over. I want it to remember where it is in the array and be able to continue even if the user has gone to a different page.

This is what I have so far, but it will break if I switch to a different page before clicking on the button.

function iAmCarousel() {
    var describe = document.getElementById("describe");
    var describeArray = [];
        describeArray[0] = "Front End Web Developer";
        describeArray[1] = "Responsive Design nut";
        describeArray[2] = "Photoshop nerd";
        describeArray[3] = "soon to be husband";
    var refreshButton = document.getElementById("refresh");
    var index = localStorage.getItem("Index");

    describe.innerText = describeArray[index];

    refreshButton.onclick = function() {
        while(index < describeArray.length) {
            index++;
            localStorage.setItem("Index", index);
            if(index == describeArray.length) {
                index = 0;
            }
            describe.innerText = describeArray[index];
            break;
        }
    }
}
iAmCarousel();
Was it helpful?

Solution

Because "Index" will not be set in localStorage, and calling getIndex() on a non-existant key returns null. You're left with describeArray[null], which won't work (and will give you undefined).

var index = localStorage.getItem("Index");

if (index === null) {
    index = 0;
}

describe.innerText = describeArray[index];

... or you can just do var index = localStorage.getItem("Index") || 0; (via short circuit evaluation)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top