Skip to content

How to store my actions in cookies through JavaScript? [closed]

I currently have a checkbox. I want to implement a method as described below~

When the user clicks on the checkbox and it turns into a red background state, this action can be stored in a cookie using javascript. When the web page is refreshed, the red background state is still Exist, how can I write it to achieve it?

label input {
  display: none;
label i {
  display: block;
  width: 10px;
  height: 10px;
  border: 1px solid;
  background: red;
label input:checked ~ i {
  display: block;
  background-image: url("");
  background-size: cover;
  <input type="checkbox">




You can set cookies with Javascript Browser DOM:

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";

This example was taken from w3schools^^

From here, you can make a cookie to be like document.cookie = "background_state = 1; expires=..."

And then in your code, you simple do something like:

function getCookie(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(';').shift();

Credit: Get cookie by name

And from here you do something along the lines of: (at the start of your code)

if(getCookie(background_state) //<-- this is referring to the value (if it's 1 its true, if 0 it's false) ){ };