You can use cookies for storing the hexcodes then take it from cookies even when page refreshes..
Here is the JavaScript code:
window.addEventListener('DOMContentLoaded', function() {
var cookieValue = getCookie('backgroundColor'),
btns = document.querySelectorAll('.color-btn');
if (cookieValue) {
setBackgroundColor(cookieValue);
}
Array.from(btns).forEach(function(btn) {
btn.addEventListener('click', function() {
var color = this.getAttribute('data-color');
setBackgroundColor(color);
});
});
});
function setBackgroundColor(color) {
document.body.style.backgroundColor = color;
setCookie('backgroundColor', color);
}
function getCookie(name) {
var cookies = document.cookie.split(';'),
cookie = cookies.find(function(str) { return str.indexOf(name + '=') === 0; });
if (cookie) {
return cookie.split('=')[1];
}
return null;
}
function setCookie(name, value) {
document.cookie = name + '=' + value;
}
CSS:
body { background: red; }
button { padding: 1em; }
[data-color="red"] { background: red; }
[data-color="blue"] { background: blue; }
[data-color="green"] { background: green; }
HTML:
<button class="color-btn" data-color="red"></button>
<button class="color-btn" data-color="blue"></button>
<button class="color-btn" data-color="green"></button>
Note that the code used here for storing cookies gets deleted when the page closes..
So the user has to change it everytime..
You can prevent that by adding this code, (this keeps it for a year, change it to your wish) ↓
var expiry = new Date();
expiry.setFullYear(expiry.getFullYear() + 1);
document.cookie = name + '=' + value + '; expires=' + expiry.toUTCString() + ';';
CLICK HERE to find out more related problems solutions.