Sling Academy
Home/JavaScript/Building Simple Date Pickers and Ranges Manually in JavaScript

Building Simple Date Pickers and Ranges Manually in JavaScript

Last updated: December 12, 2024

Date pickers are integral in web applications allowing users to conveniently select dates. Building a simple date picker manually in JavaScript can deepen your understanding of DOM manipulation and event handling. In this article, we will guide you through creating a basic date picker and handling date ranges.

Setting Up the HTML Structure

First, we'll create a basic structure for our date picker. The essential components include an input box to display the selected date and a div element for the calendar.


<div id="datePickerContainer">
  <input type="text" id="dateInput" placeholder="Select a date" readonly>
  <div id="calendar" style="display:none">
    <div id="monthAndYear">
      <button id="prevMonth"><<</button>
      <span id="currentMonthAndYear"></span>
      <button id="nextMonth">>>>/button>
    </div>
    <table id="calendarTable">
      <thead>
        <tr>
          <th>Sun</th>
          <th>Mon</th>
          <th>Tue</th>
          <th>Wed</th>
          <th>Thu</th>
          <th>Fri</th>
          <th>Sat</th>
        </tr>
      </thead>
      <tbody id="calendarBody">
      </tbody>
    </table>
  </div>
</div>

Styling the Date Picker

Next, let's add some CSS to ensure our date picker looks neat.


#calendar {
  background: white;
  border: 1px solid #aaa;
  position: absolute;
}
#monthAndYear span {
  display: inline-block;
  width: 100px;
  text-align: center;
}
#calendarTable th, #calendarTable td {
  width: 30px;
  text-align: center;
}

Building the JavaScript Functionality

Let's write the JavaScript needed to populate the calendar, navigate months, and select dates.


const dateInput = document.getElementById('dateInput');
const calendar = document.getElementById('calendar');
const currentMonthAndYear = document.getElementById('currentMonthAndYear');
const calendarBody = document.getElementById('calendarBody');
let currentDate = new Date();

function loadCalendar() {
  const month = currentDate.getMonth();
  const year = currentDate.getFullYear();
  currentMonthAndYear.textContent = `${currentDate.toLocaleString('default', { month: 'long' })} ${year}`;

  // Remove any existing table rows
  calendarBody.innerHTML = '';

  const firstDay = new Date(year, month).getDay();
  const daysInMonth = 32 - new Date(year, month, 32).getDate();
  let date = 1;
  for (let i = 0; i < 6; i++) {
    let row = document.createElement('tr');
    for (let j = 0; j < 7; j++) {
      if (i === 0 && j < firstDay) {
        const cell = document.createElement('td');
        row.appendChild(cell);
      } else if (date > daysInMonth) {
        break;
      } else {
        const cell = document.createElement('td');
        cell.textContent = date;
        cell.onclick = () => selectDate(year, month, date);
        row.appendChild(cell);
        date++;
      }
    }
    calendarBody.appendChild(row);
  }
}

function showCalendar() {
  calendar.style.display = 'block';
  loadCalendar();
}

function selectDate(year, month, day) {
  dateInput.value = `${month + 1}/${day}/${year}`;
  calendar.style.display = 'none';
}

// Event listeners

dateInput.addEventListener('focus', showCalendar);
document.getElementById('prevMonth').onclick = () => {
  currentDate.setMonth(currentDate.getMonth() - 1);
  loadCalendar();
};
document.getElementById('nextMonth').onclick = () => {
  currentDate.setMonth(currentDate.getMonth() + 1);
  loadCalendar();
};

This script enables the display of a basic calendar filled with the days of the month and allows navigation between months using previous and next buttons. By clicking on a date, the date is automatically input into the text field, and the calendar disappears.

Enhancing with Date Range Selection

For date range selection, you can add another input box and modify the selection logic to handle a start and an end date. When a start date is already chosen, a second click should finalize the date range.


let startDate = null;

function selectDateRange(year, month, day) {
  if (!startDate) {
    startDate = new Date(year, month, day);
    dateInput.value = `From: ${startDate.toLocaleDateString()}`;
  } else {
    const endDate = new Date(year, month, day);
    dateInput.value += ` To: ${endDate.toLocaleDateString()}`;
    startDate = null;
    calendar.style.display = 'none';
  }
}

In the revised function selectDateRange, make sure to switch the month and day in the toLocaleDateString method to fit the desired date format style. Handling both single date and date range selection with clear user interfaces should enhance functionality and convenience for your calendar needs.

Next Article: Implementing Custom Repeating Events (e.g., Weekly Meetings) in JavaScript

Previous Article: Calculating Age or Time Spans from Birthdates in JavaScript

Series: Date and Time in JavaScript: Basic to Advanced Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration