2024 年 8 月

網頁

[JS] Simple Calendar

參考 Learn How to Code a Simple JavaScript Calendar and Datepicker 這篇教學,做了一個簡單的月曆。

const previousMonth = document.querySelector('.previous-month');
const nextMonth = document.querySelector('.next-month');
const yearMonth = document.querySelector('.year-month');
const day = document.querySelector('.day');

let today = new Date();

// returns the full year of a date
// 4 digits
let year = today.getFullYear();

// returns the month (0 to 11) of a date
let month = today.getMonth();

showCalendar();

// 上個月
previousMonth.addEventListener('click', (e) => {
  e.preventDefault();

  month--;

  if (month < 0) {
    year--;
    month = 11;
  }

  showCalendar();
});

// 下個月
nextMonth.addEventListener('click', (e) => {
  e.preventDefault();

  month++;

  if (month > 11) {
    year++;
    month = 0;
  }

  showCalendar();
});

// function
function showCalendar() {
  yearMonth.innerHTML = `${year} / ${month + 1}`;

  // 當月第一天
  const firstDay = new Date(year, month, 1);

  // returns the day of the week (0 to 6) of a date
  // Sunday = 0, Monday = 1, ....
  const firstDayIndex = firstDay.getDay();

  // 當月最後一天
  const lastDay = new Date(year, month + 1, 0);

  // returns the day of the month (1 to 31) of a date
  const daysInMonth = lastDay.getDate();

  let dayHtml = '';

  for (let i = 1; i <= 42; i++) {
    if (i < firstDayIndex + 1) {
      dayHtml += '<div></div>';
    } else if (i > firstDayIndex + daysInMonth) {
      break;
    } else {
      const dayNumber = i - firstDayIndex;

      if (
        year === new Date().getFullYear() &&
        month === new Date().getMonth() &&
        dayNumber === new Date().getDate()
      ) {
        dayHtml += `<div class="current-date">${dayNumber}</div>`;
      } else {
        dayHtml += `<div>${dayNumber}</div>`;
      }
    }
  }

  day.innerHTML = dayHtml;
}

Demo

返回頂端