Trying to create a link with a randomly selected page in an array with Javascript

126 views Asked by At

Ok, my code is kind of messy, as I'm still a student learning the ropes of Javascript and HTML, so I'll try to explain as best I can.

I'm trying to get a "continue" link on several html pages to link to a randomly selected page from an array. I want that page to be taken out of the array, then the array to be saves in sessionStorage so that the next page's "continue" link will randomly select a link from the array that is NOT the current page, or past pages.

Here is my code:

var initialLinks=['music.html', 'test.html', 'recover.html', 'random.html']

function randomLink(){
if (typeof(Storage)!=="undefined")
{
    if (sessionStorage.links)
    {
        var storedLinks = JSON.parse(sessionStorage.links);
        var arraylink = storedLinks[Math.floor(Math.random()*storedLinks.length)];
        window.location = arraylink;

        var index = storedLinks.indexOf(arrayLink);
        if (index > -1){
            storedLinks.links.splice(index, 1);
        }
        sessionStorage.links = JSON.stringify(storedLinks);
    }
    else
    {
        sessionStorage.links = JSON.stringify(initialLinks);
        var storedLinks = JSON.parse(sessionStorage.links);
        var arraylink = storedLinks[Math.floor(Math.random()                            *storedLinks.length)];
        window.location = arraylink;

        var index = storedLinks.indexOf(arrayLink);
        if (index > -1){
            storedLinks.links.splice(index, 1);
        }
        sessionStorage.links = JSON.stringify(storedLinks);
    }
}
else
{
    document.write("Sorry, your browser does not support web storage.");
}

}

I'm getting my "continue" link to link to random pages, but the pages seem to remain in the array. Any help would be greatly appreciated. Also, I apologize in advance for my sloppy style :)

3

There are 3 answers

1
Guntram Blohm On BEST ANSWER

Looking closely, i noticed some other errors as well - arrayLink is written with a lower case L in window.location=arraylink, but in upper case elsewhere. Also, storedLinks.links.splice(index, 1); should be storedLinks.splice(index, 1); (without .links). And, once you've visited all your pages, you'll try to load an "undefined" page since you don't reinitialize your array.

This works for me (remember to save it to all your file names):

<script>

var initialLinks=['music.html', 'test.html', 'recover.html', 'random.html']

function randomLink(){
if (typeof(Storage)!=="undefined")
{
    if (sessionStorage.links)
    {
        alert("reading(1) "+sessionStorage.links);
        var storedLinks = JSON.parse(sessionStorage.links);
        if (storedLinks.length==0) {
            storedLinks=initialLinks;
        }
        var arraylink = storedLinks[Math.floor(Math.random()*storedLinks.length)];

        var index = storedLinks.indexOf(arraylink);
        if (index > -1){
            storedLinks.splice(index, 1);
        }
        sessionStorage.links = JSON.stringify(storedLinks);
        alert("saved(1) "+sessionStorage.links);
        window.location = arraylink;
    }
    else
    {
        sessionStorage.links = JSON.stringify(initialLinks);
        alert("reading(1) "+sessionStorage.links);
        var storedLinks = JSON.parse(sessionStorage.links);
        var arraylink = storedLinks[Math.floor(Math.random()                            *storedLinks.length)];

        var index = storedLinks.indexOf(arraylink);
        if (index > -1){
            storedLinks.splice(index, 1);
        }
        sessionStorage.links = JSON.stringify(storedLinks);
        alert("saved(2) "+sessionStorage.links);
        window.location = arraylink;
    }
}
else
{
    document.write("Sorry, your browser does not support web storage.");
}
}
</script>

<a href="javascript:randomLink()">Follow Link</a>
0
Jackson Ray Hamilton On

sessionStorage data only lasts for as long as the page is open. Use localStorage instead.

Also, you needed to splice your array before setting window.location. Your script would not finish executing if you hopped to another page right in the middle of a block.

I cleaned up your code a little bit and now it's working for me. Here you are:

function randomLink() {

    if (typeof window.localStorage !== 'undefined') {

        // Create links initially if non-existent.
        if (typeof localStorage.links === 'undefined') {
            localStorage.links = JSON.stringify(initialLinks);
        }

        // Get links.
        var storedLinks = JSON.parse(localStorage.links);

        // Select random link.
        if (storedLinks.length > 0) {
            var randomIndex = Math.floor(Math.random()*storedLinks.length);
            var arraylink = storedLinks[randomIndex];

            // Remove the link from the array.
            storedLinks.splice(randomIndex, 1);

            // Update the saved link.
            localStorage.links = JSON.stringify(storedLinks);

            // Now go to the link.
            window.location = arraylink;
        }
        else {
            alert('All out of links!');
        }
    }
    else {
        document.write("Sorry, your browser does not support web storage.");
    }
}

randomLink();
1
Guntram Blohm On

I'd guess that this

window.location = arraylink;

loads the new document and prevents all the rest of your javascript from happening. Put an alert(sessionStorage.links) behind every read and write operation to your sessionStorage to make sure.