logo

자바스크립트로 쿠키를 사용해 페이지 상태가 유지되게 하는 예제 📂프로그래밍

자바스크립트로 쿠키를 사용해 페이지 상태가 유지되게 하는 예제

쇼케이스

이 페이지의 체크박스는 페이지를 새로고침하거나 다른 페이지로 이동한 후에도 상태가 유지된다. 대부분의 웹페이지에서 이러한 기능은 사실 유용한 정도가 아니라 거의 필수적이라 볼 수 있다.

코드

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: 쿠키에 아이디와 상태를 저장한다.
    • saveCheckboxStates: 페이지 내의 모든 체크박스의 상태를 쿠키에 저장한다.
  • 읽기
    • getCookie: 쿠키에서 아이디에 해당하는 상태를 읽어온다.
    • restoreCheckboxStates: 체크 박스의 상태를 getCookie로 읽어와 복원한다.
  • initCheckboxPersistence: 페이지가 로드될 때 체크박스의 상태를 복원하고, 체크박스의 상태가 변경될 때마다 saveCheckboxStates를 호출한다.

같이보기