dimanche 14 octobre 2018

JavaScript - Get shuffled, non-repeated items across multiple pages

I have five different pages. Each has a button that redirects to one of the others, randomly.

I am trying to make it so that the user doesn't get to repeated pages (at least not after going through them all).

I can add a function to go through random, non-repeating stuff in the same page, but how can I make that function work across different pages, remembering which pages were already visited?

I tried saving that function in an external js file and call it in the head section of every page, but it does not work.

I also tried to use localStorage, but with no results.

Am I doing something wrong? Is this possible, to begin with?

This is what I am working with:

        localStorage.getItem("currentRemainingPages");

        var page1 = "0001.html"
        var page2 = "0002.html"
        var page3 = "0003.html"
        var page4 = "0004.html"
        var page5 = "0005.html"

        const originalPages = [page1, page2, page3, page4, page5];
        let remainingPages = [];

        function randomize() {
            if (remainingPages.length === 0) remainingPages = originalPages.slice();
            localStorage.setItem("currentRemainingPages", remainingPages);
            const {
                length
            } = remainingPages;
            const [page] = remainingPages.splice(Math.floor(Math.random() * length), 1);

            window.location.href = page;
        }
    <h1>Page 0</h1>
    <p><button onclick="randomize()" type="button">Random Page</button></p>



Aucun commentaire:

Enregistrer un commentaire