LoginSignup
2
5

More than 1 year has passed since last update.

Javascript カレンダー作成

Last updated at Posted at 2021-11-23

はじめに

本稿では下記動画にあるソースコードを解説します。

動画にあるカレンダーは、他のライブラリに依存しない実装になっています。
簡単なカレンダーが表示できれば十分、かつ、依存ライブラリを増やしたくない場合などで使えると思います。

ソースコード
https://github.com/lashaNoz/Calendar

カレンダー作成に必要な変数

// 今日の日付 EX) 2021/11/24
const date = new Date();
// 月末 EX) 2021/11/30
const lastDay = new Date(date.getFullYear(),date.getMonth() + 1,0).getDate();
// 先月末 EX) 2021/10/31 
const prevLastDay = new Date(date.getFullYear(),date.getMonth(),0).getDate();
// 月初の曜日。0 ~ 6 = 日曜 ~ 土曜 EX) 1 (2021/11/1は月曜日)
const firstDayIndex = date.getDay();
// 月末の曜日。 EX) 2 (2021/11/30は火曜)
const lastDayIndex = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDay(); 

日付表示

calndar.js
// 1.前の月
// firstDayIndexは月初の曜日。EX) 1(月曜)
// prevLastDayは先月の末日。EX) 31 (10/31)
for(let i = firstDayIndex; i>0; --i){
    days += `<div class="prev-date">${prevLastDay - i + 1}</div>`;
}

// 2.今月
const today = new Date().getDate();
for(let i = 1; i<=lastDay; ++i){
    if(i === today){
        days += `<div class="today">${i}</div>`;
    }
    else {
        days += `<div>${i}</div>`;
    }
}

// 3.次の月
const sunday = 6;
for(let i = 1; i<=sunday-lastDayIndex; ++i){
    days += `<div class="prev-date">${i}</div>`;
}

image.png

前月、次月表示ボタン押下時処理

document.querySelector(".prev").addEventListener("click", () => {
    // 前月のカレンダーを表示
    date.setMonth(date.getMonth() - 1);
    renderCalendar();
});

document.querySelector(".next").addEventListener("click", () => {
    // 次月のカレンダーを表示
    date.setMonth(date.getMonth() + 1);
    renderCalendar();
});

DOM読み込み完了後にJavascript実行(おまけ)

動画の実装だと、javascriptを読み込むタイミングによってはカレンダーが表示されません。
window.onload内に処理を定義することで、DOM読み込みが完了した後に処理が実行されます。
DOMContentLoaded イベントに処理を定義すると、DOM読み読み込み完了後に処理が実行されます。

window.addEventListener('DOMContentLoaded', () => {
    // DOM読み込み完了のタイミングで実行したい処理
    const date = new Date();

    const renderCalendar = function(){
        date.setDate(1);
        ~~~
});
2
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5