JavaScriptを使ってブラウザに「3か月分のカレンダー」を表示してみよう。
ちょっと日にちを確認するのにとっても便利である。
JavaScriptコードをブラウザで表示するために、HTMLファイルとJavaScriptファイルを作成して、HTMLファイルとJavaScriptファイルをリンクさせる。
まずは、以下の通りHTMLファイルを作成しよう。
このファイルには、カレンダーを表示するための<div>タグとJavaScriptファイルをリンクするための<script>タグが含まれる。
また、CSSでカレンダーの表示スタイルを指定している。
なお、このファイルだけを実行してもブラウザには何も表示されない。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2025年カレンダー</title>
<style>
table { border-collapse: collapse; width: 100%; margin-bottom: 20px; table-layout: fixed; }
th, td { border: 1px solid #68656D; padding: 2px; text-align: center; width: 14.28%; height: 60px; } /* セルの幅と高さをさらに調整 */
th { background-color:#EFE4E6; color: black; } /* ヘッダーの色を変更 */
.month-title { text-align: center; font-size: 1em; margin: 5px 0; color: #6718FD; } /* タイトルの色を変更 */
.today { background-color: #FFEB3B; } /* 今日の日付のスタイル */
.weekend { background-color: #FBDCF1; } /* 土日のスタイル */
.holiday { background-color: #9CF9B4; white-space: pre-line; } /* 祝日のスタイル */
</style>
</head>
<body>
<div id="calendar"></div>
<script src = "script.js"></script>
</body>
</html>
次に、以下の通りJavaScriptファイルを作成しよう。
ファイル名:script.js
//3か月分のカレンダーを表示するJavaScriptコード
// 日本の祝日データ(2025年)
const holidays = {
'2025-01-01': '元日',
'2025-01-13': '成人の日',
'2025-02-11': '建国記念の日',
'2025-02-23': '天皇誕生日',
'2025-02-24': '振替休日',
'2025-03-20': '春分の日',
'2025-04-29': '昭和の日',
'2025-05-03': '憲法記念日',
'2025-05-04': 'みどりの日',
'2025-05-05': 'こどもの日',
'2025-05-06': '振替休日',
'2025-07-21': '海の日',
'2025-08-11': '山の日',
'2025-09-15': '敬老の日',
'2025-09-23': '秋分の日',
'2025-10-13': 'スポーツの日',
'2025-11-03': '文化の日',
'2025-11-23': '勤労感謝の日',
'2025-11-24': '振替休日',
};
// カレンダーを生成する関数
function generateCalendar(year, month) {
const calendar = [];
for (let i = 0; i < 3; i++) {
const date = new Date(year, month + i, 1);
const monthDays = [];
const firstDay = (date.getDay() + 6) % 7; // 月曜日始まりに調整
const daysInMonth = new Date(year, month + i + 1, 0).getDate();
// 前月の空白を追加
for (let j = 0; j < firstDay; j++) {
monthDays.push({ date: '', day: '' });
}
// 日付を追加
for (let day = 1; day <= daysInMonth; day++) {
const currentDate = `${year}-${String(month + i + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
monthDays.push({ date: currentDate, day: holidays[currentDate] ? `${day}\n(${holidays[currentDate]})` : day });
}
calendar.push({ year, month: month + i + 1, days: monthDays });
}
return calendar;
}
// カレンダーを表示する関数
function displayCalendarHTML(calendar) {
const today = new Date();
const todayString = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
const calendarDiv = document.getElementById('calendar');
calendar.forEach(({ year, month, days }) => {
const monthTitle = document.createElement('div');
monthTitle.className = 'month-title';
monthTitle.textContent = `${year}年 ${month}月`;
calendarDiv.appendChild(monthTitle);
const table = document.createElement('table');
const headerRow = document.createElement('tr');
['月', '火', '水', '木', '金', '土', '日'].forEach(day => {
const th = document.createElement('th');
th.textContent = day;
headerRow.appendChild(th);
});
table.appendChild(headerRow);
let row = document.createElement('tr');
days.forEach((dayObj, i) => {
const cell = document.createElement('td');
const cellDate = dayObj.date;
if (cellDate === todayString) {
cell.className = 'today';
} else if (holidays[cellDate]) {
cell.className = 'holiday';
} else if (i % 7 === 5 || i % 7 === 6) { // 土日
cell.className = 'weekend';
}
cell.textContent = dayObj.day;
row.appendChild(cell);
if ((i + 1) % 7 === 0) {
table.appendChild(row);
row = document.createElement('tr');
}
});
if (row.children.length > 0) table.appendChild(row);
calendarDiv.appendChild(table);
});
}
// 使用例
const year = 2025;
const month = 3; // 0:1月,1:2月,2:3月,3:4月,4:5月
const calendar = generateCalendar(year, month);
displayCalendarHTML(calendar);
HTML構造
<div id=”calendar”></div>
カレンダーを表示するための要素である。
<script src = “script.js”></script>
<script>タグ内にJavaScriptコードのリンクを記述している。
CSSによるスタイル設定
- CSSを使用して、カレンダーの見た目を整えている。
- todayクラスは今日の日付を黄色でハイライトし、weekendクラスは土日を赤色で、holidayクラスは祝日を淡いグリーンで表示する。
JavaScriptファイル
- holidaysオブジェクトに祝日情報を追加する。
- generateCalendar関数でカレンダーを生成する。
- displayCalendarHTML関数で生成されたカレンダーをHTML形式で表示する。
- 以下の箇所で、直接年と開始月を指定している。
const year = 2025;
const month = 3; // 0:1月,1:2月,2:3月,3:4月,4:5月
作成したHTMLファイルとJavaScriptファイルを同じフォルダに保存して、このHTMLファイルをブラウザで開くと、指定された年と月から始まる3か月分のカレンダーが表示される。
ただし、祝日が2025年用のため2025年のカレンダーして利用可となる。
コメント