top of page

Just Jolly Functions

Functions: Adding a Date Picker with HTML, CSS, and JavaScript

An Interactive Date Picker is a user interface (UI) component that allows users to select a date easily by interacting with a calendar-style display. It’s commonly used in forms, scheduling applications, booking systems, and anywhere dates are required. Instead of typing a date manually, the user can simply click on a specific day in a calendar format, which greatly reduces the chances of errors in date entry.



Interactive Date Picker Code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Interactive Date Picker</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f4f4f9;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      margin: 0;
    }

    .date-picker-container {
      position: relative;
      width: 300px;
      background-color: #fff;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      text-align: center;
    }

    .input-container {
      margin-bottom: 20px;
    }

    .calendar-container {
      display: none;
      position: absolute;
      top: 50px;
      left: 0;
      width: 100%;
      background-color: white;
      border: 1px solid #ccc;
      border-radius: 8px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
      z-index: 1;
    }

    .calendar-header {
      background-color: #4CAF50;
      color: white;
      padding: 10px;
      font-size: 1.2rem;
    }

    .calendar-days {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      gap: 5px;
      padding: 10px;
    }

    .calendar-days div {
      padding: 10px;
      cursor: pointer;
      text-align: center;
    }

    .calendar-days div:hover {
      background-color: #ddd;
      border-radius: 50%;
    }

    .calendar-days .selected {
      background-color: #4CAF50;
      color: white;
      border-radius: 50%;
    }

    .calendar-footer {
      padding: 10px;
      text-align: center;
    }

    .calendar-footer button {
      background-color: #4CAF50;
      color: white;
      border: none;
      padding: 5px 10px;
      border-radius: 5px;
      cursor: pointer;
    }

    .calendar-footer button:hover {
      background-color: #45a049;
    }

    #date-input {
      padding: 10px;
      width: 100%;
      font-size: 1rem;
      border: 1px solid #ccc;
      border-radius: 5px;
      box-sizing: border-box;
    }
  </style>
</head>
<body>

  <div class="date-picker-container">
    <div class="input-container">
      <input type="text" id="date-input" placeholder="Select a Date" readonly onclick="toggleCalendar()">
    </div>
    <div class="calendar-container" id="calendar">
      <div class="calendar-header">
        <span id="month-year"></span>
      </div>
      <div class="calendar-days" id="days"></div>
      <div class="calendar-footer">
        <button onclick="clearDate()">Clear</button>
      </div>
    </div>
  </div>

  <script>
    const dateInput = document.getElementById("date-input");
    const calendar = document.getElementById("calendar");
    const monthYear = document.getElementById("month-year");
    const daysContainer = document.getElementById("days");

    let selectedDate = null;
    let currentMonth = new Date().getMonth();
    let currentYear = new Date().getFullYear();

    // Toggle calendar visibility
    function toggleCalendar() {
      calendar.style.display = (calendar.style.display === "block") ? "none" : "block";
      renderCalendar();
    }

    // Render calendar for the current month and year
    function renderCalendar() {
      const firstDay = new Date(currentYear, currentMonth, 1);
      const lastDay = new Date(currentYear, currentMonth + 1, 0);
      const daysInMonth = lastDay.getDate();
      const startDay = firstDay.getDay();
      const totalDays = [];
      
      // Set month and year in the calendar header
      monthYear.innerText = `${getMonthName(currentMonth)} ${currentYear}`;

      // Prepare days array
      for (let i = 0; i < startDay; i++) {
        totalDays.push("");
      }

      for (let day = 1; day <= daysInMonth; day++) {
        totalDays.push(day);
      }

      // Fill the calendar with days
      daysContainer.innerHTML = "";
      totalDays.forEach((day, index) => {
        const dayElement = document.createElement("div");
        if (day === "") {
          dayElement.classList.add("empty");
        } else {
          dayElement.innerText = day;
          dayElement.addEventListener("click", () => selectDate(day));
        }
        daysContainer.appendChild(dayElement);
      });
    }

    // Select a date from the calendar
    function selectDate(day) {
      selectedDate = new Date(currentYear, currentMonth, day);
      const formattedDate = formatDate(selectedDate);
      dateInput.value = formattedDate;
      calendar.style.display = "none";
    }

    // Format date as dd-mm-yyyy
    function formatDate(date) {
      const day = String(date.getDate()).padStart(2, "0");
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const year = date.getFullYear();
      return `${day}-${month}-${year}`;
    }

    // Get month name
    function getMonthName(month) {
      const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
      return months[month];
    }

    // Clear the selected date
    function clearDate() {
      selectedDate = null;
      dateInput.value = "";
    }
  </script>

</body>
</html>

Explanation of the Code:


1. HTML Structure:

  • The container is wrapped inside a div with a class of date-picker-container.

  • It contains:

    • An input field where the user can see or select the date.

    • A calendar that is shown/hidden when the user clicks the input field.

    • A button to clear the selected date.


2. CSS Styling:

  • The .date-picker-container is styled to be centered on the screen with a clean and modern design.

  • The .calendar-container is initially hidden and shown when the input field is clicked.

  • The calendar's days are displayed using a grid layout, with the current date highlighted.

  • A hover effect is added to the calendar days to enhance interactivity.

  • The button in the footer clears the selected date when clicked.


3. JavaScript Functionality:

  • Toggling the Calendar: Clicking on the input field toggles the visibility of the calendar popup.

  • Rendering the Calendar: The renderCalendar() function dynamically generates the days for the current month, considering the start day and the number of days in the month.

  • Selecting a Date: When a user clicks a day, the date is formatted and displayed in the input field, and the calendar is hidden.

  • Clearing the Date: The "Clear" button allows the user to remove the selected date from the input field.


Customization Options:

  1. Date Format: You can adjust the date format as per your region (e.g., mm/dd/yyyy or yyyy-mm-dd).

  2. Month and Year Navigation: Add buttons to navigate between months (e.g., next/previous buttons) to let users move across different months.

  3. Styling: Modify the design of the calendar (e.g., colors, fonts, sizes) to suit your post's theme.

  4. Localization: You can localize the month names and day names based on the user's region.


This simple, interactive date picker provides a user-friendly way to select dates and is a great example of combining HTML, CSS, and JavaScript.

bottom of page