Untitled
unknown
plain_text
16 days ago
3.1 kB
2
Indexable
Never
const daysContainer = document.querySelector(".days"), nextBtn = document.querySelector(".next-btn"), prevBtn = document.querySelector(".prev-btn"), month = document.querySelector(".month"), todayBtn = document.querySelector(".today-btn"); const months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ]; const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; const date = new Date(); console.log(date.getDate().toString()+"/"+(date.getMonth()+1).toString()+"/"+date.getFullYear().toString()); let currentDate = new Date(); console.log(currentDate.toCustomDateString); let currentMonth = date.getMonth(); let currentYear = date.getFullYear(); function renderCalendar() { date.setDate(1); const firDay = new Date(currentYear, currentMonth, 1); const lstDay = new Date(currentYear, currentMonth + 1, 0); const lastDayIndex = lstDay.getDay(); const lastDayDate = lstDay.getDate(); const prevLastDay = new Date(currentYear, currentMonth, 0); const prevLastDayDate = prevLastDay.getDate(); const nextDays = 7 - lastDayIndex - 1; month.innerHTML = `${months[currentMonth]} ${currentYear}`; let days = ""; for (let x = firDay.getDay(); x > 0; x--) { days += `<div class="day prev">${prevLastDayDate - x + 1}</div>`; } for (let i = 1; i <= lastDayDate; i++) { if ( i === new Date().getDate() && currentMonth === new Date().getMonth() && currentYear === new Date().getFullYear() ) { days += `<div class="day today">${i}</div>`; } else { days += `<div class="day " data-day="${i}">${i}</div>`; } } for (let j = 1; j <= nextDays; j++) { days += `<div class="day next" data-day="${j}">${j}</div>`; } daysContainer.innerHTML=days; const allDays = document.querySelectorAll("div.day:not(.prevBtn):not(.nextBtn)"); allDays.forEach(days => { days.addEventListener('click', () => { const selectedDay = days.getAttribute('div.day'); console.log(`${selectedDay} ${months[currentMonth]} ${currentYear}`); }); }); hideTodayBtn(); daysContainer.innerHTML = days; } renderCalendar(); nextBtn.addEventListener("click", () => { currentMonth++; if (currentMonth > 11) { currentMonth = 0; currentYear++; } renderCalendar(); }); prevBtn.addEventListener("click", () => { currentMonth--; if (currentMonth < 0) { currentMonth = 11; currentYear--; } renderCalendar(); }); todayBtn.addEventListener("click", () => { currentMonth = date.getMonth(); currentYear = date.getFullYear(); renderCalendar(); }); function hideTodayBtn() { if ( currentMonth === new Date().getMonth() && currentYear === new Date().getFullYear() ) { todayBtn.style.display = "none"; } else { todayBtn.style.display = "flex"; } }
Leave a Comment