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?
JavaScript
x
15
15
1
label input {
2
display: none;
3
}
4
label i {
5
display: block;
6
width: 10px;
7
height: 10px;
8
border: 1px solid;
9
background: red;
10
}
11
label input:checked ~ i {
12
display: block;
13
background-image: url("https://img.magiclen.org/albums/webpage-icon-font/shut-003.png");
14
background-size: cover;
15
}
JavaScript
1
4
1
<label>
2
<input type="checkbox">
3
<i></i>
4
</label>
Advertisement
Answer
You can set cookies with Javascript Browser DOM:
JavaScript
1
2
1
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";
2
This example was taken from w3schools^^ https://www.w3schools.com/js/js_cookies.asp
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:
JavaScript
1
6
1
function getCookie(name) {
2
const value = `; ${document.cookie}`;
3
const parts = value.split(`; ${name}=`);
4
if (parts.length === 2) return parts.pop().split(';').shift();
5
}
6
Credit: Get cookie by name
And from here you do something along the lines of: (at the start of your code)
JavaScript
1
2
1
if(getCookie(background_state) //<-- this is referring to the value (if it's 1 its true, if 0 it's false) ){DOM.edit.css.here... };
2