Vanilla JavaScript Projects

Project 63, Forms and input

Date Range Picker

Pick a start and end date the way booking sites do: two months side by side, taken dates crossed out and the nights counted for you.

Main API
Date, Intl.DateTimeFormat
Input
Mouse and keyboard
Dependencies
None
Your browser
Checking

Choose your dates

Click a start date, then an end date. Taken dates are crossed out. Use the arrow keys inside the calendar, or a preset.

Minimum 2 nights
Check inPick a date
Check outPick a date
Nights0

How it works

  1. Build the grid from datesFor each month the script works out which weekday the 1st falls on, adds empty cells, then one button per day.
  2. Two clicks make a rangeThe first click sets check in. The second sets check out if it is later, long enough and has no taken nights in between.
  3. Keyboard as a gridOnly one day is in the Tab order. Arrow keys move a day or a week, and the calendar moves to the next month when needed.
function monthGrid(year, month) {
  const firstWeekday = (new Date(year, month, 1).getDay() + 6) % 7; // Monday first
  const days = new Date(year, month + 1, 0).getDate();              // days in month
  const cells = Array(firstWeekday).fill(null);
  for (let d = 1; d <= days; d++) cells.push(new Date(year, month, d));
  return cells;
}
const nights = Math.round((checkOut - checkIn) / 86400000);