Simple calendar with highlight multiple date
Simple Calendar
by Vishnuprasad ps
HTML
<div id="calendar-container">
<button id="prev-month">Previous</button>
<span id="month-year"></span>
<button id="next-month">Next</button>
<div id="calendar"></div>
</div>
CSS
body {
font-family: Arial, sans-serif;
margin: 0;
}
#calendar-container {
text-align: center;
}
#calendar {
display: grid;
grid-template-columns: repeat(7, 1fr);
gap: 5px;
width: 280px;
margin: 20px auto;
}
#calendar div {
padding: 10px;
text-align: center;
border: 1px solid #ccc;
}
#calendar .header {
font-weight: bold;
background-color: #f0f0f0;
}
#calendar .today {
background-color: #ff0;
font-weight: bold;
}
#calendar .highlight {
background-color: #0f0;
font-weight: bold;
}
button {
margin: 5px;
}
JavaScript
document.addEventListener('DOMContentLoaded', () => {
const calendarContainer = document.getElementById('calendar-container');
const calendar = document.getElementById('calendar');
const monthYear = document.getElementById('month-year');
const prevMonthButton = document.getElementById('prev-month');
const nextMonthButton = document.getElementById('next-month');
let date = new Date();
// Define the specific highlight dates for each month
const highlightDays = {
5: [18, 20], // June (0-indexed, so month 5 is June)
};
function renderCalendar() {
calendar.innerHTML = ''; // Clear previous calendar
const year = date.getFullYear();
const month = date.getMonth();
const today = new Date().getDate();
const isCurrentMonth = new Date().getFullYear() === year && new Date().getMonth() === month;
const daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const monthDays = new Date(year, month + 1, 0).getDate();
monthYear.innerText = `${date.toLocaleString('default', { month: 'long' })} ${year}`;
// Generate calendar header
daysOfWeek.forEach(day => {
const dayHeader = document.createElement('div');
dayHeader.classList.add('header');
dayHeader.innerText = day;
calendar.appendChild(dayHeader);
});
// Generate empty cells for days of the week before the first day of the month
const firstDay = new Date(year, month, 1).getDay();
for (let i = 0; i < firstDay; i++) {
const emptyCell = document.createElement('div');
calendar.appendChild(emptyCell);
}
// Generate days of the month
for (let day = 1; day <= monthDays; day++) {
const dayCell = document.createElement('div');
dayCell.innerText = day;
if (isCurrentMonth && day === today) {
dayCell.classList.add('today');
} else if (highlightDays[month] && highlightDays[month].includes(day)) {
dayCell.classList.add('highlight');
}
...