Datepicker in JavaScript Code with Example

Datepicker in JavaScript Code with Example
Project: Vanilla JavaScript Datepicker
Author: Tomek Uzarowski
Edit Online: View on CodePen
License: MIT

This JavaScript code example helps you to create a datepicker. It gets the current date, dynamically creates a calendar widget, and attaches it to the input field. When a user clicks the input field the calendar widget displays to pick the date.

You can integrate this date picker to get date input from the users for different purposes. It’s the best fit for date entry for date of birth, event date, scheduling something, or a general-purpose date selection. If you’re working on a project where you need to filter data based on selected dates, you may use this dropdown date picker.

How to Create Datepicker In Javascript Code With Example

First of all, load the Normalize CSS (optional) and Font Awesome 5 CSS by adding the following CDN link to the head tag of your webpage.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/css/all.min.css'>

Now, create an input element with the type “text” and define its class name “date-input”. Place this input inside your form element and also set a Font Awesome calendar icon just above the input. The following is the basic structure for the date picker:

<div class="form-container">
   <form>
      <i class="far fa-calendar-alt"></i>
      <input type="text" placeholder="Pick a date" class="date-input">
   </form>
</div>

Now, style the date picker using the following CSS styles. You can modify the CSS rules in order to customize the date picker according to your needs.

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  background-color: rgba(0, 0, 0, 0.04);
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.cd__main{
background: #e43a15;  /* fallback for old browsers */
background: -webkit-linear-gradient(to right, #e65245, #e43a15);  /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #e65245, #e43a15) !important; /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}
.form-container {
  align-items: center;
  display: flex;
  height: 100vh;
  justify-content: center;
}
.form-container form {
  background-color: #fff;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
  position: relative;
}
.form-container form.open .calendar-popup {
  opacity: 1;
}
.form-container form i {
  padding: 0 10px 0 15px;
}
.form-container form input {
  background-color: transparent !important;
  border: none;
  border-left: 1px solid #eee;
  padding: 15px 25px;
}
.form-container .calendar-popup {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
  opacity: 0;
  padding: 10px;
  position: absolute;
  top: calc(100% + 5px);
  transition: all 0.1s linear;
  width: 100%;
}
.form-container .calendar-popup .month-and-year {
  align-items: center;
  display: flex;
  text-align: center;
  text-transform: uppercase;
}
.form-container .calendar-popup .month-and-year h4 {
  width: 100%;
}
.form-container .calendar-popup .button {
  background-color: transparent;
  border: none;
  font-weight: bold;
  outline: none;
  position: absolute;
  top: 15px;
}
.form-container .calendar-popup .button:hover {
  cursor: pointer;
}
.form-container .calendar-popup .button.prev {
  left: 10px;
}
.form-container .calendar-popup .button.next {
  right: 10px;
}
.form-container .calendar-popup table {
  font-size: 12px;
  width: 100%;
}
.form-container .calendar-popup table tr {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  padding: 5px 0;
}
.form-container .calendar-popup table tr th,
.form-container .calendar-popup table tr td {
  text-align: center;
}
.form-container .calendar-popup table .day:hover {
  cursor: pointer;
}

Add the following JavaScript function:

class Calendar {
    constructor(inputSelector) {
        this.input = document.querySelector(inputSelector);
        this.form = this.input.parentElement;
        this.popupContainer = null;
        this.monthContainer = null;
        this.tableContainer = null;
        this.table = document.createElement("table");
        this.months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
        this.selectedMonth = new Date().getMonth();
        this.selectedYear = new Date().getFullYear();
        
        this.buildCalendar();
        this.setMainEventListener();
    }
    
    buildCalendar() {
        this.popupContainer = document.createElement("div");
        this.popupContainer.classList.add("calendar-popup");
        this.form.appendChild(this.popupContainer);

        
        this.monthContainer = document.createElement("div");
        this.monthContainer.classList.add("month-and-year");
        this.monthContainer.innerHTML = `<h4>${this.getMonth()} ${this.getYear()}</h4>`;
        this.popupContainer.appendChild(this.monthContainer);

        this.createButtons();

        this.populateTable(this.selectedMonth, this.selectedYear);
    }

    createButtons() {
        const prev = document.createElement("button");
        prev.classList.add('button', 'prev');
        prev.innerHTML = "<i class='fas fa-chevron-left'></i>";
        const next = document.createElement("button");
        next.classList.add('button', 'next');
        next.innerHTML = "<i class='fas fa-chevron-right'></i>";

        prev.addEventListener("click", e => {
            e.preventDefault();
            this.updateMonth(this.selectedMonth - 1);
        });

        next.addEventListener("click", e => {
            e.preventDefault();
            this.updateMonth(this.selectedMonth + 1);
        });

        this.popupContainer.appendChild(prev);
        this.popupContainer.appendChild(next);
    }

    populateTable(month, year) {
        this.table.innerHTML = "";

        const namesRow = document.createElement("tr");
        ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].forEach(name => {
            const th = document.createElement("th");
            th.innerHTML = name;
            namesRow.appendChild(th);
        });
        this.table.appendChild(namesRow);

        const tempDate = new Date(year, month, 1);
        let firstMonthDay = tempDate.getDay();
        firstMonthDay = firstMonthDay === 0 ? 7 : tempDate.getDay();

        const daysInMonth = this.getDaysInMonth(month, year);
        const j = daysInMonth + firstMonthDay - 1;

        let tr = document.createElement("tr");

        if (firstMonthDay-1 !== 0) {
            tr = document.createElement("tr");
            this.table.appendChild(tr);
        }

        for (let i=0; i<firstMonthDay-1; i++) {
            const td = document.createElement("td");
            td.innerHTML = "";
            tr.appendChild(td);
        }

        for (let i = firstMonthDay-1; i<j; i++) {
            if(i % 7 === 0){
                tr = document.createElement("tr");
                this.table.appendChild(tr);
            }

            const td = document.createElement("td");
            td.innerText = i - firstMonthDay + 2;
            td.dayNr = i - firstMonthDay + 2;
            td.classList.add("day");

            td.addEventListener("click", e => {
                const selectedDay = e.target.innerHTML;
                this.fillInput(selectedDay);
                this.hideCalendar();
            });

            tr.appendChild(td);
        }

        this.popupContainer.appendChild(this.table);
    }

    fillInput(day) {
        day = day < 10 ? "0" + day : day;
        let month = null;
        month = this.selectedMonth < 9 ? "0" + (this.selectedMonth + 1) : this.selectedMonth + 1;
        this.input.value = `${day}.${month}.${this.selectedYear}`;
    }

    updateMonth(month) {
        this.selectedMonth = month;
        if (this.selectedMonth < 0) {
            this.selectedYear--;
            this.selectedMonth = 11;
        } else if (this.selectedMonth > 11) {
            this.selectedYear++;
            this.selectedMonth = 0;
        }
        this.monthContainer.innerHTML = `<h4>${this.months[this.selectedMonth]} ${this.selectedYear}</h4>`;

        this.populateTable(this.selectedMonth, this.selectedYear)
    }
    
    getMonth() {
        return this.months[this.selectedMonth];
    }

    getYear() {
        return this.selectedYear;
    }

    getDaysInMonth(month, year) {
        return new Date(year, month + 1, 0).getDate();
    }
    
    hideCalendar() {
        this.form.classList.remove("open");
    }

    setMainEventListener() {
        this.input.addEventListener("click", e => {
            this.form.classList.toggle("open");
            
            if(!this.form.classList.contains("open")) {
                this.hideCalendar();
            }
        });
    }
}

new Calendar(".date-input");

That’s all! hopefully, you have successfully created a date picker in JavaScript. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply