Generate a single index.html file that implements a fully functional date range picker…
- User
Generate a single index.html file that implements a fully functional date range picker component.
The component should display a calendar interface allowing users to:
Navigate through months and years using clear controls (e.g., "Previous", "Next"). Select a start date by clicking on a date cell. Select an end date after the start date by clicking on another date cell. Visually highlight the entire range of dates selected, from the start date to the end date, including the start and end dates themselves. Reset the selection if a new date is clicked that is before the currently selected start date, starting a new range selection from that new date. All necessary HTML structure, CSS styling, and JavaScript logic must be contained within this single index.html file. Avoid linking external stylesheets or scripts; embed everything directly. The goal is a self-contained, interactive date range selector ready to be opened directly in a browser.
Assistant
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Date Range Picker</title> <style> /* Basic Reset & Body Style */ body { font-family: sans-serif; display: flex; justify-content: center; align-items: flex-start; /* Align to top */ min-height: 100vh; background-color: #f4f4f4; padding-top: 30px; box-sizing: border-box; } /* Component Container */ .date-range-picker { background-color: #fff; border-radius: 8px; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1); padding: 20px; width: 320px; /* Fixed width for better calendar layout */ display: flex; flex-direction: column; align-items: center; } /* Selected Range Display */ #selected-range { margin-bottom: 15px; padding: 10px; border: 1px solid #eee; border-radius: 4px; background-color: #f9f9f9; width: 90%; text-align: center; font-size: 0.9em; color: #333; min-height: 1.2em; /* Ensure space even when empty */ } /* Calendar Container */ .calendar { width: 100%; } /* Calendar Header (Month/Year Nav) */ .calendar-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; padding: 0 5px; } .calendar-header button { background: none; border: none; font-size: 1.4em; cursor: pointer; color: #007bff; padding: 5px 10px; border-radius: 4px; transition: background-color 0.2s ease; } .calendar-header button:hover { background-color: #eef; } .calendar-header button:active { background-color: #ddf; } #month-year { font-weight: bold; font-size: 1.1em; color: #333; } /* Weekdays Header */ .calendar-weekdays { display: grid; grid-template-columns: repeat(7, 1fr); text-align: center; margin-bottom: 5px; font-size: 0.8em; color: #666; font-weight: bold; } .calendar-weekdays div { padding: 5px 0; } /* Dates Grid */ .calendar-dates { display: grid; grid-template-columns: repeat(7, 1fr); gap: 2px; /* Small gap between cells */ } /* Individual Date Cells */ .calendar-date { display: flex; justify-content: center; align-items: center; height: 36px; /* Fixed height */ border: 1px solid transparent; /* Placeholder for border */ border-radius: 4px; cursor: pointer; font-size: 0.9em; transition: background-color 0.2s ease, border-color 0.2s ease, color 0.2s ease; position: relative; /* For potential pseudo-elements if needed */ } .calendar-date:not(.disabled):hover { background-color: #eee; border-color: #ddd; } .calendar-date.disabled { color: #ccc; cursor: default; background-color: #f9f9f9; } /* --- Selection Styling --- */ .calendar-date.selected-start, .calendar-date.selected-end { background-color: #007bff; color: #fff; border-color: #0056b3; font-weight: bold; } .calendar-date.in-range { background-color: #cce5ff; /* Lighter blue for range */ color: #004085; border-radius: 0; /* Remove radius for middle elements */ border-color: transparent; } /* --- Range Edge Styling Adjustments --- */ .calendar-date.selected-start.in-range { border-top-right-radius: 0; border-bottom-right-radius: 0; } .calendar-date.selected-end.in-range { border-top-left-radius: 0; border-bottom-left-radius: 0; } /* Handle single day selection appearance */ .calendar-date.selected-start.selected-end { border-radius: 4px; } /* --- Adjust range background for row starts/ends --- */ /* When a cell is in range AND starts a row (or is the start date) */ .calendar-date.in-range:nth-child(7n + 1), .calendar-date.selected-start.in-range { border-top-left-radius: 4px; border-bottom-left-radius: 4px; } /* When a cell is in range AND ends a row (or is the end date) */ .calendar-date.in-range:nth-child(7n), .calendar-date.selected-end.in-range { border-top-right-radius: 4px; border-bottom-right-radius: 4px; } </style> </head> <body> <div class="date-range-picker"> <div id="selected-range">Select a start and end date</div> <div class="calendar"> <div class="calendar-header"> <button id="prev-month"><</button> <span id="month-year"></span> <button id="next-month">></button> </div> <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-dates" id="calendar-dates"> <!-- Date cells will be generated here by JavaScript --> </div> </div> </div> <script> document.addEventListener('DOMContentLoaded', () => { const monthYearEl = document.getElementById('month-year'); const calendarDatesEl = document.getElementById('calendar-dates'); const prevMonthBtn = document.getElementById('prev-month'); const nextMonthBtn = document.getElementById('next-month'); const selectedRangeEl = document.getElementById('selected-range'); let currentDate = new Date(); let startDate = null; let endDate = null; // --- Helper Functions --- // Function to format date as YYYY-MM-DD for data attributes function formatDateISO(date) { if (!date) return ''; const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`; } // Function to parse YYYY-MM-DD string to local Date object at midnight function parseISODate(isoString) { if (!isoString) return null; const [year, month, day] = isoString.split('-').map(Number); // Create date in local timezone at midnight to avoid timezone shifts return new Date(year, month - 1, day); } // Function to format date for display function formatDateDisplay(date) { if (!date) return ''; return date.toLocaleDateString(undefined, { // Use browser's locale year: 'numeric', month: 'short', day: 'numeric' }); } // --- Core Calendar Rendering --- function renderCalendar() { const year = currentDate.getFullYear(); const month = currentDate.getMonth(); // 0-indexed // Update header monthYearEl.textContent = currentDate.toLocaleDateString(undefined, { year: 'numeric', month: 'long' }); // Clear previous dates calendarDatesEl.innerHTML = ''; // Calendar calculations const firstDayOfMonth = new Date(year, month, 1); const lastDayOfMonth = new Date(year, month + 1, 0); const daysInMonth = lastDayOfMonth.getDate(); const firstDayWeekday = firstDayOfMonth.getDay(); // 0=Sun, 1=Mon,... // Add empty cells for days before the 1st of the month for (let i = 0; i < firstDayWeekday; i++) { const emptyCell = document.createElement('div'); emptyCell.classList.add('calendar-date', 'disabled'); calendarDatesEl.appendChild(emptyCell); } // Add date cells for the current month for (let day = 1; day <= daysInMonth; day++) { const cell = document.createElement('div'); const cellDate = new Date(year, month, day); const cellDateISO = formatDateISO(cellDate); cell.classList.add('calendar-date'); cell.textContent = day; cell.dataset.date = cellDateISO; // Store date as YYYY-MM-DD // Apply selection styles if (startDate && cellDateISO === formatDateISO(startDate)) { cell.classList.add('selected-start'); } if (endDate && cellDateISO === formatDateISO(endDate)) { cell.classList.add('selected-end'); } if (startDate && endDate && cellDate > startDate && cellDate < endDate) { cell.classList.add('in-range'); } // Handle single day selection visual (start and end are same) if (startDate && endDate && formatDateISO(startDate) === formatDateISO(endDate) && cellDateISO === formatDateISO(startDate)) { cell.classList.add('selected-start', 'selected-end'); // Both classes } // Add 'in-range' to start/end for background coloring logic if (startDate && endDate && cellDate >= startDate && cellDate <= endDate) { cell.classList.add('in-range'); } cell.addEventListener('click', handleDateClick); calendarDatesEl.appendChild(cell); } // Add empty cells for days after the last day of the month to fill the grid const totalCells = firstDayWeekday + daysInMonth; const remainingCells = (totalCells % 7 === 0) ? 0 : 7 - (totalCells % 7); for (let i = 0; i < remainingCells; i++) { const emptyCell = document.createElement('div'); emptyCell.classList.add('calendar-date', 'disabled'); calendarDatesEl.appendChild(emptyCell); } updateSelectedRangeDisplay(); } // --- Update Selected Range Text --- function updateSelectedRangeDisplay() { if (startDate && endDate) { // Sort dates just in case internal logic allows end < start temporarily const displayStart = startDate <= endDate ? startDate : endDate; const displayEnd = startDate <= endDate ? endDate : startDate; selectedRangeEl.textContent = `${formatDateDisplay(displayStart)} - ${formatDateDisplay(displayEnd)}`; } else if (startDate) { selectedRangeEl.textContent = `Start: ${formatDateDisplay(startDate)} - Select end date`; } else { selectedRangeEl.textContent = 'Select a start and end date'; } } // --- Event Handlers --- function handleDateClick(event) { const clickedCell = event.target; if (!clickedCell.classList.contains('calendar-date') || clickedCell.classList.contains('disabled')) { return; // Ignore clicks on non-date cells or disabled cells } const clickedDateISO = clickedCell.dataset.date; const clickedDate = parseISODate(clickedDateISO); // Get local date at midnight if (!clickedDate) return; // Safety check // Logic for selecting start/end dates if (!startDate || (startDate && endDate) || clickedDate < startDate) { // 1. No start date selected OR // 2. Both start and end are already selected (start new range) OR // 3. Clicked date is before the current start date (start new range) startDate = clickedDate; endDate = null; // Reset end date } else if (startDate && !endDate && clickedDate >= startDate) { // Start date is selected, no end date, and clicked date is valid end date endDate = clickedDate; } // No else needed: if clickedDate < startDate when startDate is set but not endDate, // it's handled by the first condition (resetting the range). // Re-render the calendar to reflect the new selection state renderCalendar(); } prevMonthBtn.addEventListener('click', () => { currentDate.setMonth(currentDate.getMonth() - 1); renderCalendar(); }); nextMonthBtn.addEventListener('click', () => { currentDate.setMonth(currentDate.getMonth() + 1); renderCalendar(); }); // --- Initial Render --- renderCalendar(); }); </script> </body> </html>Explanation:
-
HTML Structure:
- A main container
div.date-range-picker. - A
div#selected-rangeto display the chosen date range textually. - A
div.calendarholds the calendar interface. .calendar-headercontains the previous/next month buttons (<button>) and the month/year display (<span>)..calendar-weekdaysshows the abbreviated day names (Sun-Sat)..calendar-datesis the grid where the actual date cells will be generated by JavaScript.
- A main container
-
CSS Styling (
<style>block):- Provides basic layout, centering, and styling for the picker container.
- Styles the calendar header, buttons, weekdays, and the date grid (
display: grid). - Crucially, it defines styles for different date cell states:
.calendar-date: Default appearance.:hover: Feedback on mouseover..disabled: For cells outside the current month or potentially unavailable dates..selected-start: Highlights the chosen start date..selected-end: Highlights the chosen end date..in-range: Styles the dates between the start and end dates.
- Includes specific CSS rules (
border-radiusadjustments) to make the range highlighting look continuous across rows and connect smoothly with the start/end dates.
-
JavaScript Logic (
<script>block):- State Variables:
currentDate(tracks the displayed month/year),startDate,endDate. - DOM References: Gets references to the necessary HTML elements.
formatDateISO/parseISODate: Helper functions to reliably convert betweenDateobjects andYYYY-MM-DDstrings (used fordata-dateattributes), ensuring dates are handled consistently at local midnight.formatDateDisplay: Formats dates nicely for the#selected-rangedisplay area.renderCalendar():- Calculates the year and month to display.
- Updates the
#month-yeartext. - Clears the previous date cells.
- Determines the first day's weekday and total days in the month.
- Adds placeholder
.disabledcells for days before the 1st. - Loops through each day of the month:
- Creates a
div.calendar-date. - Sets its text content (the day number).
- Adds a
data-dateattribute with theYYYY-MM-DDformat. - Applies
.selected-start,.selected-end, and.in-rangeclasses based on comparisons with thestartDateandendDatestate variables. Special care is taken to handle the visual look of a single selected day and the edges of the range highlight. - Attaches the
handleDateClickevent listener to each valid date cell. - Appends the cell to the
.calendar-datesgrid.
- Creates a
- Adds trailing
.disabledcells to fill the last row of the grid if needed. - Calls
updateSelectedRangeDisplay()after rendering.
updateSelectedRangeDisplay(): Updates the text in the#selected-rangediv based on whetherstartDateandendDateare set.handleDateClick(event):- Triggered when a date cell is clicked.
- Gets the date string from the
data-dateattribute and parses it. - Implements the core selection logic:
- If no start date, or if resetting (clicked before start, or range already complete), set the clicked date as the new
startDateand clearendDate. - If only
startDateis set and the clicked date is on or after it, set the clicked date asendDate.
- If no start date, or if resetting (clicked before start, or range already complete), set the clicked date as the new
- Calls
renderCalendar()to update the visual highlighting immediately.
- Navigation Event Listeners: Attached to the previous/next month buttons. They modify the
currentDatestate variable and callrenderCalendar()to show the new month. - Initial Call:
renderCalendar()is called once when the script loads to display the initial calendar view (current month).
- State Variables:
This single file contains everything needed. Just save it as
index.htmland open it in a web browser.-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.