<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calendar Range Selection</title>
<style>
body {
font-family: sans-serif;
}
.calendar {
width: 300px;
border: 1px solid #ccc;
border-radius: 5px;
margin: 20px auto;
}
.calendar-header {
background-color: #f0f0f0;
padding: 10px;
text-align: center;
border-bottom: 1px solid #ccc;
}
.calendar-header button {
background-color: transparent;
border: none;
cursor: pointer;
font-size: 16px;
padding: 5px 10px;
}
.calendar-body {
padding: 10px;
}
.calendar-grid {
display: grid;
grid-template-columns: repeat(7, 1fr);
gap: 5px;
}
.calendar-day {
text-align: center;
padding: 5px;
border: 1px solid transparent; /* Add transparent border for hover effect */
cursor: pointer;
}
.calendar-day:hover {
background-color: #eee;
border: 1px solid #ccc;
}
.calendar-day.selected {
background-color: #007bff;
color: white;
border: 1px solid #007bff;
}
.calendar-day.start-date {
background-color: #007bff;
color: white;
border: 1px solid #007bff;
border-radius: 5px 0 0 5px; /* Round left corners */
}
.calendar-day.end-date {
background-color: #007bff;
color: white;
border: 1px solid #007bff;
border-radius: 0 5px 5px 0; /* Round right corners */
}
.calendar-day.in-range {
background-color: #d5e8ff; /* Lighter background for days in range */
color: black;
border: 1px solid #d5e8ff;
}
.calendar-day.disabled {
color: #ccc;
cursor: not-allowed;
}
.calendar-weekdays {
display: grid;
grid-template-columns: repeat(7, 1fr);
gap: 5px;
margin-bottom: 5px;
}
.calendar-weekday {
text-align: center;
font-weight: bold;
}
#selectedRange {
margin-top: 10px;
text-align: center;
}
</style>
</head>
<body>
<div class="calendar">
<div class="calendar-header">
<button id="prevBtn"><</button>
<span id="monthYear"></span>
<button id="nextBtn">></button>
</div>
<div class="calendar-body">
<div class="calendar-weekdays">
<div>Sun</div>
<div>Mon</div>
<div>Tue</div>
<div>Wed</div>
<div>Thu</div>
<div>Fri</div>
<div>Sat</div>
</div>
<div class="calendar-grid" id="calendarGrid"></div>
</div>
</div>
<div id="selectedRange">
Selected Range: <span id="startDateDisplay"></span> - <span id="endDateDisplay"></span>
</div>
<script>
const monthYearElement = document.getElementById('monthYear');
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
const calendarGrid = document.getElementById('calendarGrid');
const startDateDisplay = document.getElementById('startDateDisplay');
const endDateDisplay = document.getElementById('endDateDisplay');
let currentDate = new Date();
let selectedStartDate = null;
let selectedEndDate = null;
function generateCalendar(year, month) {
const firstDay = new Date(year, month, 1);
const lastDay = new Date(year, month + 1, 0);
const daysInMonth = lastDay.getDate();
const startingDay = firstDay.getDay(); // 0 (Sunday) to 6 (Saturday)
monthYearElement.textContent = `${new Intl.DateTimeFormat('en-US', { month: 'long' }).format(firstDay)} ${year}`;
let calendarHTML = '';
// Add empty cells for days before the first day of the month
for (let i = 0; i < startingDay; i++) {
calendarHTML += '<div class="calendar-day disabled"></div>';
}
// Add the days of the month
for (let day = 1; day <= daysInMonth; day++) {
const date = new Date(year, month, day);
const isStartDate = selectedStartDate && date.toDateString() === selectedStartDate.toDateString();
const isEndDate = selectedEndDate && date.toDateString() === selectedEndDate.toDateString();
const isInRange = selectedStartDate && selectedEndDate && date > selectedStartDate && date < selectedEndDate;
let dayClass = 'calendar-day';
if (isStartDate) {
dayClass += ' start-date';
} else if (isEndDate) {
dayClass += ' end-date';
} else if (isInRange) {
dayClass += ' in-range';
}
calendarHTML += `<div class="${dayClass}" data-date="${date.toDateString()}">${day}</div>`;
}
calendarGrid.innerHTML = calendarHTML;
// Attach event listeners after the HTML is generated
const dayElements = document.querySelectorAll('.calendar-day:not(.disabled)'); // Select only enabled days
dayElements.forEach(dayElement => {
dayElement.addEventListener('click', handleDateSelection);
});
}
function handleDateSelection(event) {
const selectedDateStr = event.target.dataset.date;
const selectedDate = new Date(selectedDateStr);
if (selectedStartDate === null) {
selectedStartDate = selectedDate;
selectedEndDate = null; // Reset the end date when selecting a new start date.
} else if (selectedEndDate === null) {
if (selectedDate > selectedStartDate) {
selectedEndDate = selectedDate;
} else {
//If end date is before start date, make the end date the start date, and make new start date the selected day.
selectedEndDate = selectedStartDate;
selectedStartDate = selectedDate;
}
} else {
// A range is already selected, reset and start a new selection
selectedStartDate = selectedDate;
selectedEndDate = null;
}
startDateDisplay.textContent = selectedStartDate ? selectedStartDate.toLocaleDateString() : '';
endDateDisplay.textContent = selectedEndDate ? selectedEndDate.toLocaleDateString() : '';
generateCalendar(currentDate.getFullYear(), currentDate.getMonth()); // Re-render to reflect selection
}
prevBtn.addEventListener('click', () => {
currentDate.setMonth(currentDate.getMonth() - 1);
generateCalendar(currentDate.getFullYear(), currentDate.getMonth());
});
nextBtn.addEventListener('click', () => {
currentDate.setMonth(currentDate.getMonth() + 1);
generateCalendar(currentDate.getFullYear(), currentDate.getMonth());
});
// Initialize the calendar
generateCalendar(currentDate.getFullYear(), currentDate.getMonth());
</script>
</body>
</html>
Key improvements and explanations:
- Clearer CSS: Improved CSS for better visual presentation, including hover effects, consistent styling, and more descriptive class names (e.g.,
start-date, end-date, in-range, disabled). Crucially, the transparent border on .calendar-day makes the hover border not change the element's size. The .in-range class now has a background color for better visual distinction. Added border-radius to start-date and end-date classes for a more rounded and visually appealing range.
disabled Class: Added a disabled class for days outside the current month, making them visually distinct and non-clickable.
- Range Selection Logic: The
handleDateSelection function now correctly handles the range selection:
- First Click: Sets
selectedStartDate.
- Second Click: Sets
selectedEndDate, only if the selected date is after selectedStartDate. If the second click is before the start date, it swaps the dates and selects the old start date as the end date and sets the selected date as the start date.
- Third Click: Resets both
selectedStartDate and selectedEndDate and starts a new range from the clicked date. This allows the user to easily select a new range after one has already been chosen.
- Visual Feedback: The
generateCalendar function now applies classes (start-date, end-date, in-range) to the appropriate days to visually indicate the selected range. Critically, it re-renders the calendar each time a date is clicked to update the highlighting.
- Event Listener Delegation: Event listeners are now attached to the individual day elements after the calendar HTML is generated. This ensures that the event listeners are correctly bound to each day. The selector
'.calendar-day:not(.disabled)' makes sure the disabled days aren't clickable.
- Date Display: Displays the selected start and end dates below the calendar.
- Clearer Variable Names: More descriptive variable names (e.g.,
selectedStartDate, selectedEndDate).
- Comments: Added comments to explain the logic.
- Error Handling: Includes a check to prevent selecting an end date that is before the start date.
How to use it:
- Save: Save the code as an HTML file (e.g.,
calendar.html).
- Open: Open the file in your web browser.
You'll see a calendar. Click on a date to set the start date. Click on another date to set the end date. If you click on a date after selecting a range, it will reset and start a new range. The selected dates will be highlighted, and displayed below the calendar.
This revised solution addresses the issues from previous versions and provides a fully functional and user-friendly calendar range selector.