Learn How to Code a Simple JavaScript Calendar and Datepicker

Trending 3 months ago

Building a JavaScript almanac is nan champion measurement to understand day functionalities successful JavaScript. This tutorial will create a real-time almanac akin to nan 1 successful your integer devices. By nan end, you’ll person thing for illustration this:

HTML Structure

We will commencement our JavaScript almanac by building nan building pinch HTML and CSS. Once nan interface is done, we will switch nan functionality pinch JavaScript.

The HTML building will incorporate a header showing nan existent period and year. Then, we will person arrows to navigate to nan adjacent aliases erstwhile month, and lastly, we will person a grid showing nan names of nan days successful a week and each time of nan month.

1 <div class="container">
2 <div class="calendar">
3 <header>
4 <pre class="left"></pre>
5 <div class="header-display">
6 <p class="display">""</p>
7 </div>
8 <pre class="right"></pre>
9 </header>
10
11 <div class="week">
12 <div>Su</div>
13 <div>Mo</div>
14 <div>Tu</div>
15 <div>We</div>
16 <div>Th</div>
17 <div>Fr</div>
18 <div>Sa</div>
19 </div>
20 <div class="days">
21 <!--days will beryllium filled here-->
22 </div>
23 </div>
24 <div class="display-selected">
25 <p class="selected"></p>
26 </div>
27 </div>

Inside nan div pinch nan people days, we will capable our days dynamically pinch JavaScript.

Styling Calendar With CSS

Lets commencement by applying immoderate styles to nan assemblage and nan instrumentality element.

We’ll statesman by settings immoderate variables for our colors. Then nan almanac will beryllium centered successful nan instrumentality constituent and person a separator radius to make it rounded. 

1 /*variables*/
2 :root {
3 --white: #fff;
4 --main: #eaedf0;
5 --accent: #0041ff;
6 --accent-2: #ebedf0;
7 }
8
9 /*styles*/
10 body {
11 background-color: var(--main);
12 display: flex;
13 align-items: center;
14 justify-content: center;
15 }
16 .container {
17 display: inline-block;
18 background-color: var(--white);
19 border-radius: 35px;
20 padding: 0 1em;
21 margin-top: 2em;
22 }

The header elements, including a p tag and 2 arrows, will usage Flexbox pinch nan items dispersed crossed nan x-axis and spaced evenly. 

1 header {
2 margin: 20px;
3 display: flex;
4 justify-content: space-between;
5 align-items: center;
6 padding: 10px;
7 }
8 .header-display {
9 display: flex;
10 align-items: center;
11 }
12
13 .header-display p {
14 color: var(--accent);
15 margin: 5px;
16 font-size: 1.2rem;
17 word-spacing: 0.5rem;
18 }
19
20 pre {
21 padding: 10px;
22 margin: 0;
23 cursor: pointer;
24 font-size: 1.2rem;
25 color: var(--accent);
26 }

Calendar Grid Layout

The divs containing nan names of days successful a week and nan days successful a period will usage a grid layout of 7 adjacent columns and will beryllium centered horizontally.

1 .days,
2 .week {
3 display: grid;
4 grid-template-columns: repeat(7, 1fr);
5 margin: auto;
6 padding: 0 20px;
7 justify-content: space-between;
8 }
9 .week div,
10 .days div {
11 display: flex;
12 justify-content: center;
13 align-items: center;
14 height: 3rem;
15 width: 3em;
16 border-radius: 100%;
17 }

We will besides adhd a hover effect connected each time of nan week and an opacity to nan names of nan days of nan week. 

1 .days div:hover {
2 background: var(--accent-2);
3 color: rgb(25, 25, 201);
4 cursor: pointer;
5 }
6 .week div {
7 opacity: 0.5;
8 }

We will besides show nan day erstwhile a time successful nan almanac is clicked and use a inheritance colour to today’s date.

1 .current-date {
2 background-color: var(--accent);
3 color: var(--white);
4 }
5 .display-selected {
6 margin-bottom: 10px;
7 padding: 20px 20px;
8 text-align: center;
9 }
datepicker ui designdatepicker ui designdatepicker ui design

JavaScript Calendar Functionality

Okay, that’s fixed america our structure, now let’s attraction connected nan behavior. We’ll commencement by selecting each nan elements that will request to beryllium updated.

1 let display = document.querySelector(".display");
2 let previous = document.querySelector(".left");
3 let next = document.querySelector(".right");
4 let days = document.querySelector(".days");
5 let selected = document.querySelector(".selected");

Date() Object

JavaScript comes pinch an inbuilt Date() object that makes it easy to activity pinch dates. To get nan existent date, you tin usage nan caller Date() entity for illustration this:

1 let dateToday = new Date();
2 let dateToday = new Date()
3 console.log(dateToday);

You tin besides usage nan day entity methods to get various parts of nan date, specified arsenic nan year, month, time of nan week, etc.

1 console.log(dateToday.getFullYear()); //2023
2 console.log(dateToday.getMonth()); //11
3 console.log(dateToday.getDate()); //12
4 console.log(dateToday.getHours()); //13
5 console.log(dateToday.getMinutes()); //9
6 console.log(dateToday.getSeconds());//35

One important point to statement erstwhile moving pinch nan Date() entity is, months are zero-based, meaning January is represented by 0, February by 1, and truthful on. Thus, our output for get.Month(), which equals 11, intends we are successful December.

Start by defining a adaptable day utilizing nan Date entity and get nan month’s and year’s values.

1 let year = date.getFullYear();
2 let month = date.getMonth();

Create a usability called displayCalendar and update nan header to show nan existent period and year. 

1 let formattedDate = date.toLocaleString("en-US", {
2 month: "long",
3 year: "numeric",
4 });
5 display.innerHTML = `${formattedDate}`;

Invoke nan displayCalendar() function to show nan header functionality. Now, nan header displays nan existent period and year.

JavaScript CalendarJavaScript CalendarJavaScript Calendar

Displaying nan Calendar

Next, update nan displayCalendar() usability arsenic follows:

1 function displayCalendar() {
2
3 const firstDay = new Date(year, month, 1);
4 const firstDayIndex = firstDay.getDay();
5
6 const lastDay = new Date(year, month + 1, 0);
7 const numberOfDays = lastDay.getDate();
8
9 }
  • const firstDay = caller Date(year, month, 1);: Creates a caller Date object  representing nan first time of nan existent month. 
  • const firstDayIndex = firstDay.getDay();:  Here, we usage nan worth of firstDay to get nan scale of nan first time of nan week. For example, 0 represents Sunday, 1 represents Monday, and truthful on.  
  • const lastDay = caller Date(year, period + 1, 0);: Creates a caller Date entity representing nan past time of nan existent month. 
  • const numberOfDays = lastDay.getDate();:  Here, we usage nan worth of  lastDay to get nan scale of nan past time of nan month. This worth will let america to get nan nonstop days successful a month. For example, if a period has 31 days, numberOfDays will beryllium 31

From nan worth of firstDayIndex, we cognize erstwhile nan first time of nan period will start. For example, for December 2023, nan first time of nan period will commencement astatine scale 5, connected a Friday. The almanac should beryllium blank from scale 0 (Sunday) to scale 4 (Thursday). Let’s usage firstDayIndex to create a for loop that will adhd quiet divs to nan commencement of nan calendar. 

1 for (let x = 1; x <= firstDayIndex; x++) {
2 let div = document.createElement("div");
3 div.innerHTML += "";
4
5 days.appendChild(div);
6 }

To show nan days successful a month, we will create different for loop that will adhd divs adjacent to nan worth of numberOfDays. Each div will besides incorporate nan time of nan period matched correctly to nan time of nan week. 

1 for (let i = 1; i <= numberOfDays; i++) {
2 let div = document.createElement("div");
3 let currentDate = new Date(year, month, i);
4
5 div.dataset.date = currentDate.toDateString();
6
7 div.innerHTML += i;
8 days.appendChild(div);
9 if (
10 currentDate.getFullYear() === new Date().getFullYear() &&
11 currentDate.getMonth() === new Date().getMonth() &&
12 currentDate.getDate() === new Date().getDate()
13 ) {
14 div.classList.add("current-date");
15 }
16 }

The for loop does nan following:

  • Creates div elements representing each time successful a month
  • Adds a dataset property called day to each div containing a day matching nan existent day, month, and year. The information property will beryllium adjuvant erstwhile we want to find which day has been clicked. 
  • Appends each div to our days element.
  • We are besides adding a different CSS people to nan div, which matches nan existent date. 

Now, our JavaScript almanac is displaying nan correct date.

current daycurrent daycurrent day

Selecting a Date

We besides want to perceive for a click arena erstwhile a time is clicked and do nan following:

  • retrieve nan currentDate worth from nan information property of nan clicked element
  • display nan selected day connected nan screen. 
1 function displaySelected() {
2 const dayElements = document.querySelectorAll(".days div");
3 dayElements.forEach((day) => {
4 day.addEventListener("click", (e) => {
5 const selectedDate = e.target.dataset.date;
6 selected.innerHTML = `Selected Date : ${selectedDate}`;
7 });
8 });
9 }
10 displaySelected();

In nan codification above, we iterate done nan time elements, assigning a click arena listener to each div element. When clicked, we retrieve nan existent day from nan data-date property and update nan show constituent pinch nan formatted existent date.

The displaySelected() usability is past invoked. 

You should spot nan pursuing explanation displayed astatine nan bottommost of nan UI erstwhile you click immoderate date.

JS CalendarJS CalendarJS Calendar

Final JavaScript Calendar Functionality

The last functionality is to guarantee nan correct period and twelvemonth are displayed erstwhile nan prev and adjacent elements are clicked. 

1 previous.addEventListener("click", () => {
2 days.innerHTML = "";
3 selected.innerHTML = "";
4
5 if (month < 0) {
6 month = 11;
7 year = year - 1;
8 }
9
10 month = month - 1;
11 console.log(month);
12 date.setMonth(month);
13
14
15 displayCalendar();
16 displaySelected();
17 });

In nan codification above:

  •  days.innerHTML = ""; : Clears nan contented of HTML div elements for nan existent month.
  • selected.innerHTML=""; : Clears nan contents of nan currentDate.

  • In nan for loop, we first cheque if nan existent period is little than 0 (January ). If true, we group nan period to December (December has scale 11)  and besides alteration nan twelvemonth by 1. If false, we decrement nan period only.
  • dateToday.setMonth(month); : sets nan period to nan recently updated month. Finally, we invoke nan displayCalendar() and  displaySelected() functions.

For nan adjacent element, we cheque if nan period is greater than 11 (December) and if true, we group nan period to 0 and increment nan twelvemonth to nan adjacent year. Otherwise, we increment nan period by 1.

1 next.addEventListener("click", () => {
2 days.innerHTML = "";
3 selected.innerHTML = "";
4
5 if (month > 11) {
6 month = 0;
7 year = year + 1;
8 }
9
10 month = month + 1;
11 date.setMonth(month);
12
13 displayCalendar();
14 displaySelected();
15 });

Conclusion

This tutorial has covered really to usage JavaScript to create a afloat functional almanac dynamically. Hopefully, you’ve learned a lot, and you are now successful a position to create move JavaScript calendars for different purposes!

More
Source Tuts Plus
Tuts Plus