Learn How to Code a Simple JavaScript Calendar and Datepicker

Constructing a JavaScript calendar is the easiest way to grasp date functionalities in JavaScript. This tutorial will create a real-time calendar just like the one in your digital units. By the top, you’ll have one thing like this:

HTML Construction

We’ll begin our JavaScript calendar by constructing the construction with HTML and CSS. As soon as the interface is finished, we are going to substitute the performance with JavaScript.

The HTML construction will include a header displaying the present month and 12 months. Then, we may have arrows to navigate to the following or earlier month, and lastly, we may have a grid displaying the names of the times in per week and every day of the month.

1
<div class="container">
2
  <div class="calendar">
3
    <header>
4
      <pre class="left"></pre>
5
      <div class="header-display">
6
        <p class="show">""</p>
7
      </div>
8
      <pre class="proper"></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 probably be stuffed here-->
22
    </div>
23
  </div>
24
   <div class="display-selected">
25
        <p class="chosen"></p>
26
      </div>
27
</div>

Contained in the div with the category days, we are going to fill our days dynamically with JavaScript.

Styling Calendar With CSS

Lets begin by making use of some kinds to the physique and the container factor.

We’ll start by settings some variables for our colours. Then the calendar will probably be centered within the container factor and have a border 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
/*kinds*/
10
physique {
11
  background-color: var(--main);
12
  show: flex;
13
  align-items: heart;
14
  justify-content: heart;
15
}
16
.container {
17
  show: inline-block;
18
  background-color: var(--white);
19
  border-radius: 35px;
20
  padding: 0 1em;
21
  margin-top: 2em;
22
}

The header parts, together with a p tag and two arrows, will use Flexbox with the objects unfold throughout the x-axis and spaced evenly. 

1
header {
2
  margin: 20px;
3
  show: flex;
4
  justify-content: space-between;
5
  align-items: heart;
6
  padding: 10px;
7
}
8
.header-display {
9
  show: flex;
10
  align-items: heart;
11
}
12

13
.header-display p {
14
  colour: 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
  colour: var(--accent);
26
}

Calendar Grid Structure

The divs containing the names of days in per week and the times in a month will use a grid structure of seven equal columns and will probably be centered horizontally.

1
.days,
2
.week {
3
  show: 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
  show: flex;
12
  justify-content: heart;
13
  align-items: heart;
14
  top: 3rem;
15
  width: 3em;
16
  border-radius: 100%;
17
}

We will even add a hover impact on every day of the week and an opacity to the names of the times of the week. 

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

We will even show the date when a day within the calendar is clicked and apply a background colour to at this time’s date.

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

JavaScript Calendar Performance

Okay, that’s given us our construction, now let’s give attention to the conduct. We’ll begin by choosing all the weather that may must be up to date.

1
let show = doc.querySelector(".show");
2
let earlier = doc.querySelector(".left");
3
let subsequent = doc.querySelector(".proper");
4
let days = doc.querySelector(".days");
5
let chosen = doc.querySelector(".chosen");

Date() Object

JavaScript comes with an inbuilt Date() object that makes it straightforward to work with dates. To get the present date, you need to use the new Date() object like this:

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

You may as well use the date object strategies to get numerous elements of the date, such because the 12 months, month, day of the week, and many others.

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 necessary factor to notice when working with the Date() object is, months are zero-based, which means January is represented by 0, February by 1, and so forth. Thus, our output for get.Month(), which equals 11, means we’re in December.

Begin by defining a variable date utilizing the Date object and get the month’s and 12 months’s values.

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

Create a perform referred to as displayCalendar and replace the header to indicate the present month and 12 months. 

1
let formattedDate = date.toLocaleString("en-US", {
2
  month: "lengthy",
3
  12 months: "numeric",
4
});
5
show.innerHTML = `${formattedDate}`;

Invoke the displayCalendar() perform to show the header performance. Now, the header shows the present month and 12 months.

JavaScript CalendarJavaScript CalendarJavaScript Calendar

Displaying the Calendar

Subsequent, replace the displayCalendar() perform as follows:

1
perform displayCalendar() {
2

3
    const firstDay = new Date(12 months, month, 1);
4
    const firstDayIndex = firstDay.getDay(); 
5

6
    const lastDay = new Date(12 months, month + 1, 0);
7
    const numberOfDays = lastDay.getDate(); 
8

9
}

  • const firstDay = new Date(12 months, month, 1);: Creates a brand new Date object  representing the primary day of the present month. 
  • const firstDayIndex = firstDay.getDay();:  Right here, we use the worth of firstDay to get the index of the primary day of the week. For instance, 0 represents Sunday, 1 represents Monday, and so forth.  
  • const lastDay = new Date(12 months, month + 1, 0);: Creates a brand new Date object representing the final day of the present month. 
  • const numberOfDays = lastDay.getDate();:  Right here, we use the worth of  lastDay to get the index of the final day of the month. This worth will enable us to get the precise days in a month. For instance, if a month has 31 days, numberOfDays will probably be 31

From the worth of firstDayIndex, we all know when the primary day of the month will begin. For instance, for December 2023, the primary day of the month will begin at index 5, on a Friday. The calendar needs to be clean from index 0 (Sunday) to index 4 (Thursday). Let’s use firstDayIndex to create a for loop that may add empty divs to the beginning of the calendar. 

1
for (let x = 1; x <= firstDayIndex; x++) {
2
  let div = doc.createElement("div");
3
  div.innerHTML += "";
4

5
  days.appendChild(div);
6
}

To show the times in a month, we are going to create one other for loop that may add divs equal to the worth of numberOfDays. Every div will even include the day of the month matched accurately to the day of the week. 

1
for (let i = 1; i <= numberOfDays; i++) {
2
  let div = doc.createElement("div");
3
  let currentDate = new Date(12 months, 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 the next:

  • Creates div parts representing every day in a month
  • Provides a dataset attribute referred to as date to every div containing a date matching the present day, month, and 12 months. The info attribute will probably be useful once we need to decide which date has been clicked. 
  • Appends every div to our days factor.
  • We’re additionally including a unique CSS class to the div, which matches the present date. 

Now, our JavaScript calendar is displaying the right date.

current daycurrent daycurrent day

Deciding on a Date

We additionally need to hear for a click on occasion when a day is clicked and do the next:

  • retrieve the currentDate worth from the information attribute of the clicked factor
  • show the chosen date on the display screen. 
1
perform displaySelected() {
2
  const dayElements = doc.querySelectorAll(".days div");
3
  dayElements.forEach((day) => {
4
    day.addEventListener("click on", (e) => {
5
      const selectedDate = e.goal.dataset.date;
6
      chosen.innerHTML = `Chosen Date : ${selectedDate}`;
7
    });
8
  });
9
}
10
displaySelected();

Within the code above, we iterate by the day parts, assigning a click on occasion listener to every div factor. When clicked, we retrieve the present date from the data-date attribute and replace the show factor with the formatted present date.

The displaySelected() perform is then invoked. 

You must see the next label displayed on the backside of the UI while you click on any date.

JS CalendarJS CalendarJS Calendar

Last JavaScript Calendar Performance

The ultimate performance is to make sure the right month and 12 months are displayed when the prev and subsequent parts are clicked. 

1
earlier.addEventListener("click on", () => {
2
  days.innerHTML = "";
3
  chosen.innerHTML = "";
4

5
  if (month < 0) {
6
    month = 11;
7
    12 months = 12 months - 1;
8
  }
9

10
  month = month - 1;
11
  console.log(month);
12
  date.setMonth(month);
13

14

15
  displayCalendar();
16
  displaySelected();
17
});

Within the code above:

  •  days.innerHTML = ""; : Clears the content material of HTML div parts for the present month.
  • chosen.innerHTML=""; : Clears the contents of the currentDate.

  • Within the for loop, we first verify if the present month is lower than 0 (January ). If true, we set the month to December (December has index 11)  and likewise lower the 12 months by 1. If false, we decrement the month solely.
  • dateToday.setMonth(month); : units the month to the newly up to date month. Lastly, we invoke the displayCalendar() and  displaySelected() capabilities.

For the following factor, we verify if the month is bigger than 11 (December) and if true, we set the month to 0 and increment the 12 months to the following 12 months. In any other case, we increment the month by 1.

1
subsequent.addEventListener("click on", () => {
2
  days.innerHTML = "";
3
  chosen.innerHTML = "";
4

5
  if (month > 11) {
6
    month = 0;
7
    12 months = 12 months + 1;
8
  }
9

10
  month = month + 1;
11
  date.setMonth(month);
12

13
  displayCalendar();
14
  displaySelected();
15
});

Conclusion

This tutorial has coated how one can use JavaScript to create a totally practical calendar dynamically. Hopefully, you’ve discovered rather a lot, and also you at the moment are able to create dynamic JavaScript calendars for various functions!

Trending Merchandise
[product_category category=”trending” per_page=”8″ columns=”2″ orderby=”date” order=”desc”].

We will be happy to hear your thoughts

Leave a reply

MyStudioCafe
Logo
Compare items
  • Total (0)
Compare
0