Newer
Older
kensho2 / calendar.js
document.addEventListener("DOMContentLoaded", () =>{
let yotei = {};
let today = new Date();
let current = new Date(today.getFullYear(), today.getMonth(), 1);
function createcalendar(date){
const week = ["日","月","火","水","木","金","土"];
const year = date.getFullYear();
const month = date.getMonth();

let calendarhtml = `<table class="calendar"><thead><tr>`;
for (let i = 0; i < 7; i++){
	if (i === 0){
calendarhtml += `<th class="日">${week[i]}</th>`;	
			} else if (i === 6){
		calendarhtml += `<th class="土">${week[i]}</th>`;
	} else {
		calendarhtml += `<th>${week[i]}</th>`;
	}
}
	calendarhtml += `</tr></thead><tbody>`;
	
	const day = new Date(year, month + 1, 0).getDate();
	const firstday = new Date(year, month, 1).getDay();
	const premonth = new Date(year, month, 0).getDate();
	let daycount = 1;
	let predaycount = premonth - firstday + 1;
	
	for (let i = 0; i<6; i++){
		calendarhtml +=`<tr>`;
		
		for(let j = 0; j<7; j++){
			if(i === 0 && j<firstday){
				calendarhtml+=`<td class="mute">${predaycount}</td>`;
				predaycount++;
			} else if (daycount>day){
				let nextmonth= daycount - day;
				calendarhtml+=`<td class="mute">${nextmonth}</td>`;
				daycount++;
			} else {
				const datekey = `${year}-${month+1}-${daycount}`;
				let eventtext = yotei[datekey]?`<div class="event">${yotei[datekey]}</div>`:"";
				if(daycount===today.getDate() && month===today.getMonth() && year===today.getFullYear()){
					calendarhtml+=`<td class="today" data-date="${datekey}">${daycount}${eventtext}</td>`;
				}
				else if (j===0||j===6){
					calendarhtml+=`<td class="off" data-date="${datekey}">${daycount}${eventtext}</td>`;
				}
				else {
					calendarhtml+=`<td data-date="${datekey}">${daycount}${eventtext}</td>`;
				}
				daycount++;
			}
		}
		calendarhtml+=`</tr>`;
		if (daycount>day) break;
	}
	
	calendarhtml+=`</tbody></table>`;
	return calendarhtml;
}

function rendCal(){
	document.getElementById("calendar").innerHTML = 
	`<div class ="calheader">
	<button id = "preview" type = "button">&lt;</button>
	<span class = "title">${current.getFullYear()}年${current.getMonth()+1}月</span>
	<button id = "next" type = "button">&gt;</button>
	</div>
	${createcalendar(current)}`;
	
	document.getElementById("preview").addEventListener("click", ()=> {
		current.setMonth(current.getMonth()-1);
		rendCal();
	});
	
	document.getElementById("next").addEventListener("click", ()=> {
		current.setMonth(current.getMonth()+1);
		rendCal();
	});
	
const query = window.location.search;//管理者モード実装
if(query ==="?admin"){

	document.querySelectorAll("#calendar td[data-date]").forEach(td => {
		td.addEventListener("click", ()=> {
			const datekey=td.getAttribute("data-date");
			const plan=prompt(`${datekey}の予定を入力してください`, yotei[datekey] || "");
			if(plan!==null){
				if(plan.trim() === ""){
					delete yotei[datekey];//空なら削除
				} else {
					yotei[datekey] = plan;//保存
				}
				rendCal();//再描画して反映
			}
		});
	});
}	
}
rendCal();
});