JavaScriptでクッキーを使用してページの状態を維持する例
ショーケース
このページのチェックボックスはページをリロードしたり別のページに移動した後でも状態が保持される。ほとんどのウェブページにおいて、この機能は有用というよりもほぼ必須と言える。
コード
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>
あまり大きな意味はない。
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>
- 書き込み
setCookie
: クッキーにIDと状態を保存する。saveCheckboxStates
: ページ内のすべてのチェックボックスの状態をクッキーに保存する。
- 読み込み
getCookie
: クッキーからIDに対応する状態を読み出す。restoreCheckboxStates
: チェックボックスの状態をgetCookie
で読み出して復元する。
initCheckboxPersistence
: ページがロードされたときにチェックボックスの状態を復元し、チェックボックスの状態が変更されるたびにsaveCheckboxStates
を呼び出す。