Canceling changing color on refresh

๐Ÿ‘:0

If you want to persist the color on refresh without the use of a server, youโ€™ll have to store it in the browser of the user. For example, you can do this by storing it in localStorage. Using this, your function could look like this:

function getRandomRgb(colorId) {
    if (localStorage.hasOwnProperty(`randomRgb-${colorId}`)) return localStorage.getItem(`randomRgb-${colorId}`)

    var num = Math.round(0xffffff * Math.random());
    var r = num >> 16;
    var g = (num >> 8) & 255;
    var b = num & 255;
    var randomRgb = "rgb(" + r + ", " + g + ", " + b + ")";

    localStorage.setItem(`randomRgb-${colorId}`, randomRgb)
    return randomRgb
}

To generate a color for a certain colorId in your example, you could do:

getRandomRgb(colorMap[z.Description])

Another way would be to store your entire colorMap in localStorage, instead of specific colors.

๐Ÿ‘:0

Am assuming that colorMap is your array where you have all colors, you should save this array in localStorage but you should stringify it first and then change your if statement in something like this

// save into local storage use this when your array is completly generated
localStorage.setItem("colorMap", JSON.stringify(colorMap));

your statement should looks like this

//check if there is colors saved in localStorage 
if(!localStorage.getItem("colorMap")){
  // generate new random values
} else { 
  // retrieve your saved array from local storage
  colorMap = JSON.parse(localStorage.getItem("colorMap"));
}

Leave a comment