JNH1994 JNH1994 - 3 months ago 14
Javascript Question

Generate a random site colour scheme using JavaScript

I am currently working on a small site and thought it would be quirky if the site adopted a random colour scheme on each visit - meaning each time a user visited the site, they would see a slightly different version.

I have attempted doing this using JavaScript but the site generates a new colour on each page visit...

Any help would be great - if it can be done solely using JS that is?



$(document).ready(function(){

// Generate random colour for the header of the site...

let colours = [
'#F8E71C',
'#1cf8b1',
'#1cb1f8',
'#c21cf8',
'#f81c3a',
];

let randomNumber = Math.floor(Math.random() * colours.length) + 1;

let header = $('.site-head');
let cardColour = $('.card__border');

localStorage.setItem("siteTheme", colours[randomNumber]);

if (localStorage.getItem("siteTheme")) {
header.css({
backgroundColor: localStorage.getItem("siteTheme"),
});

cardColour.css({
backgroundColor: localStorage.getItem("siteTheme"),
});
}

});

Answer

Your issue is that you generate a random color and then set it in localStorage, every time.

I refactored your code into functions with an initial check.

$(document).ready(function() {

    let header = $('.site-head');
    let cardColour = $('.card__border');

    if (localStorage.getItem("siteTheme")) {
        setColorScheme();
    } else {
        createColorScheme();
    }

    function createColorScheme() {
        let colours = [
            '#F8E71C',
            '#1cf8b1',
            '#1cb1f8',
            '#c21cf8',
            '#f81c3a',
        ];

        let randomNumber = Math.floor(Math.random() * colours.length) + 1;

        localStorage.setItem("siteTheme", colours[randomNumber]);

        setColorScheme();
    }

    function setColorScheme() {
        header.css({
            backgroundColor: localStorage.getItem("siteTheme"),
        });

        cardColour.css({
            backgroundColor: localStorage.getItem("siteTheme"),
        });
    }

});

Note: I think you have an error in the random generator part, sometimes the random color becomes undefined, I think it's because of the + 1.

Comments