One way to store and retrieve hexcodes is by using cookies, even when the page refreshes.
Check out the JavaScript code snippet below:
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 styling:
body { background: red; }
button { padding: 1em; }
[data-color="red"] { background: red; }
[data-color="blue"] { background: blue; }
[data-color="green"] { background: green; }
Sample HTML buttons:
<button class="color-btn" data-color="red"></button>
<button class="color-btn" data-color="blue"></button>
<button class="color-btn" data-color="green"></button>
Here is a JSFiddle link
Keep in mind that the cookie storage in this code expires when the page closes, requiring manual re-entry. To extend the duration, add the following code (which preserves it for a year, adjust as needed):
var expiry = new Date();
expiry.setFullYear(expiry.getFullYear() + 1);
document.cookie = name + '=' + value + '; expires=' + expiry.toUTCString() + ';';