How To Save Background Color In Cookie Through Button Click?
Im currently trying to learn about cookies in javascript. My question is : I have three Button Red-Green-Blue and if i click for example on red, the background color red should be
Solution 1:
You can do it like this:
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);
});
});
});
functionsetBackgroundColor(color) {
document.body.style.backgroundColor = color;
setCookie('backgroundColor', color);
}
functiongetCookie(name) {
var cookies = document.cookie.split(';'),
cookie = cookies.find(function(str) { return str.indexOf(name + '=') === 0; });
if (cookie) {
return cookie.split('=')[1];
}
returnnull;
}
functionsetCookie(name, value) {
document.cookie = name + '=' + value;
}
body { background: red; }
button { padding: 1em; }
[data-color="red"] { background: red; }
[data-color="blue"] { background: blue; }
[data-color="green"] { background: green; }
<buttonclass="color-btn"data-color="red"></button><buttonclass="color-btn"data-color="blue"></button><buttonclass="color-btn"data-color="green"></button>
Note: this demo won't work on Stack Overflow because it is sandboxed and does not accept cookies
Edit:
In the example above, I did not set an expiry date on the cookie for clarity. This means that the cookie will only stay during the current session (i.e. when you close all of your browser's tabs, it will be gone). You can choose to keep it for a longer period. For example, a year:
var expiry = newDate();
expiry.setFullYear(expiry.getFullYear() + 1);
document.cookie = name + '=' + value + '; expires=' + expiry.toUTCString() + ';';
Post a Comment for "How To Save Background Color In Cookie Through Button Click?"