자바스크립트 Local Storage를 활용한 캘린더 애플리케이션 구현

Calendar

캘린더 애플리케이션은 일정을 관리하고 날짜별로 이벤트를 표시하기 위한 유용한 도구입니다. 이번 포스트에서는 자바스크립트의 Local Storage를 활용하여 간단한 캘린더 애플리케이션을 구현하는 방법을 다루겠습니다.

요구 사항

Local Storage란?

Local Storage는 웹 브라우저에 데이터를 저장할 수 있는 기능을 제공합니다. 이를 활용하면 웹페이지에서 사용자가 입력한 데이터를 브라우저에 저장하여 나중에 불러와 사용할 수 있습니다.

애플리케이션 구현

HTML 구조

<body>
  <h1>My Calendar</h1>
  <div id="calendar">
    <!-- 캘린더 표시할 내용 -->
  </div>
</body>

자바스크립트 코드

// 캘린더에 표시할 일정 데이터
let events = [];

// Local Storage에서 데이터 불러오기
if (localStorage.getItem("events")) {
  events = JSON.parse(localStorage.getItem("events"));
} else {
  // 초기 데이터 설정
  events = [
    {
      date: "2022-01-01",
      event: "New Year's Day"
    },
    {
      date: "2022-02-14",
      event: "Valentine's Day"
    }
  ];
  localStorage.setItem("events", JSON.stringify(events));
}

// 캘린더 표시 함수
function renderCalendar() {
  // 캘린더 요소 선택
  const calendarElement = document.getElementById("calendar");

  // 캘린더 초기화
  calendarElement.innerHTML = "";

  // 현재 월과 연도 가져오기
  const currentDate = new Date();
  const currentYear = currentDate.getFullYear();
  const currentMonth = currentDate.getMonth() + 1;

  // 캘린더 테이블 생성
  const calendarTable = document.createElement("table");
  calendarTable.classList.add("calendar-table");

  // 헤더 생성
  const headerRow = document.createElement("tr");
  const daysOfWeek = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  daysOfWeek.forEach(day => {
    const th = document.createElement("th");
    th.textContent = day;
    headerRow.appendChild(th);
  });
  calendarTable.appendChild(headerRow);

  // 월별 일정 표시
  const daysInMonth = new Date(currentYear, currentMonth, 0).getDate();
  let dayCounter = 1;
  for (let i = 0; i < 6; i++) {
    const weekRow = document.createElement("tr");
    for (let j = 0; j < 7; j++) {
      if (dayCounter > daysInMonth) {
        break;
      }
      const dayCell = document.createElement("td");
      dayCell.textContent = dayCounter;

      // 해당 날짜의 일정 표시
      const eventList = document.createElement("ul");
      events.forEach(event => {
        if (event.date === `${currentYear}-${currentMonth}-${dayCounter}`) {
          const eventItem = document.createElement("li");
          eventItem.textContent = event.event;
          eventList.appendChild(eventItem);
        }
      });
      dayCell.appendChild(eventList);

      weekRow.appendChild(dayCell);
      dayCounter++;
    }
    calendarTable.appendChild(weekRow);
  }

  calendarElement.appendChild(calendarTable);
}

// 캘린더 표시
renderCalendar();

결론

위의 코드를 실행하면 Local Storage를 활용한 캘린더 애플리케이션이 동작합니다. 이제 사용자는 일정을 추가하고 삭제할 수 있으며, 새로고침해도 이전에 저장한 일정이 그대로 유지됩니다. Local Storage를 이용하면 다양한 웹 애플리케이션에서 유용하게 사용할 수 있습니다.

#webdevelopment #javascript