[Solved] How to save background color in cookie through button click?


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);
    });
  });
});

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;
}
body { background: red; }
button { padding: 1em; }
[data-color="red"] { background: red; }
[data-color="blue"] { background: blue; }
[data-color="green"] { background: green; }
<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: 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 = new Date();
expiry.setFullYear(expiry.getFullYear() + 1);
document.cookie = name + '=' + value + '; expires=" + expiry.toUTCString() + ";';

7

solved How to save background color in cookie through button click?