【JavaScript】少しリッチなカレンダーの作成
以前、シンプルなカレンダーを作成するJavaScriptのコードの記事を書きましたが、今回はボタンによって前月、次月のカレンダーを表示することができるカレンダーを作成しました。
Webアプリ、Webサイトでのカレンダー作成時の参考に。
CSSは省略しています。
<body> <div> <div class="month"> <a href="#" id="last-month"><b><</b></a> <a href="#" id="next-month"><b>></b></a> <span id="year"></span>年<span id="month"></span>月 </div> <table id="cal" class="calendar"> </table> </div> <script> 'use strict' function createCalendar(year, month) { const start = new Date(year, month, 1); // 月初 const last = new Date(year, month + 1, 0); // 月末 const startDate = start.getDate(); // 月初 const lastDate = last.getDate(); // 月末 const startDay = start.getDay(); // 月初の曜日 const lastDay = last.getDay(); // 月末の曜日 let days = []; let weekDay = []; let dayCount = 0; // 曜日カウント用 for (let i = startDate; i <= lastDate; i++) { if (i === startDate) { for (let j = 0; j < startDay; j++) { weekDay.push(''); dayCount++; } } weekDay.push(i); dayCount++; if (dayCount === 7) { days.push(weekDay); dayCount = 0; weekDay = []; } } for (let i = lastDay; i < 6; i++) { weekDay.push(''); } days.push(weekDay); let cal = `<tr> <th>日</th> <th>月</th> <th>火</th> <th>水</th> <th>木</th> <th>金</th> <th>土</th> </tr>`; for (const week of days) { cal += '<tr>'; for (const day of week) { cal += '<td class="day">' + day + '</td>'; } cal += '</tr>'; } document.getElementById('cal').innerHTML = cal; document.getElementById('year').textContent = year; document.getElementById('month').textContent = month + 1; } document.getElementById('last-month').addEventListener('click', e => { e.preventDefault(); let year = Number(document.getElementById('year').textContent); let month = Number(document.getElementById('month').textContent); year = month === 1 ? year - 1 : year; month = month === 1 ? 12 : month - 1; createCalendar(year, month - 1); }); document.getElementById('next-month').addEventListener('click', e => { e.preventDefault(); let year = Number(document.getElementById('year').textContent); let month = Number(document.getElementById('month').textContent); year = month === 12 ? year + 1 : year; month = month === 12 ? 1 : month + 1; createCalendar(year, month - 1); }); const today = new Date(); // 現在の日時 createCalendar(today.getFullYear(), today.getMonth()); </script> </body>