Example of Using Cookies in JavaScript to Maintain Page State
Showcase
The checkboxes on this page retain their state even after refreshing the page or navigating to another page. For most web pages, this feature is not merely useful but can be considered almost essential.
Code
HTML
<div align="center" style="user-select: none;">
<input type="checkbox" id="A"><label for="A">A</label>
<input type="checkbox" id="B"><label for="B">B</label>
<input type="checkbox" id="C"><label for="C">C</label>
<input type="checkbox" id="D"><label for="D">D</label>
<input type="checkbox" id="E"><label for="E">E</label>
<input type="checkbox" id="F"><label for="F">F</label>
<input type="checkbox" id="G"><label for="G">G</label>
<input type="checkbox" id="H"><label for="H">H</label>
<input type="checkbox" id="I"><label for="I">I</label>
<input type="checkbox" id="J"><label for="J">J</label>
</div>
Not particularly significant.
javascript
<script>
function setCookie(name, value) {
document.cookie = name + "=" + encodeURIComponent(value) + "; path=/";
}
function saveCheckboxStates() {
document.querySelectorAll("input[type='checkbox']").forEach(cb =>
setCookie(cb.id, cb.checked ? "1" : "0")
);
}
function getCookie(name) {
const value = "; " + document.cookie;
const parts = value.split("; " + name + "=");
if (parts.length === 2) return decodeURIComponent(parts.pop().split(";").shift());
}
function restoreCheckboxStates() {
document.querySelectorAll("input[type='checkbox']").forEach(cb => {
const saved = getCookie(cb.id);
if (saved === "1") cb.checked = true;
else if (saved === "0") cb.checked = false;
});
}
function initCheckboxPersistence() {
restoreCheckboxStates();
document.querySelectorAll("input[type='checkbox']").forEach(cb =>
cb.addEventListener("change", saveCheckboxStates)
);
}
window.addEventListener("DOMContentLoaded", () => {
initCheckboxPersistence();
});
</script>
- Writing
setCookie
: stores an id and its state in a cookie.saveCheckboxStates
: saves the states of all checkboxes on the page to cookies.
- Reading
getCookie
: reads the state corresponding to an id from the cookies.restoreCheckboxStates
: reads checkbox states viagetCookie
and restores them.
initCheckboxPersistence
: restores checkbox states when the page loads and callssaveCheckboxStates
whenever a checkbox state changes.