Create A Dynamic Calendar in HTML CSS & JavaScript

10

Build A Dynamic Calendar in HTML CSS & JavaScript Calendar in JavaScript

Hey friends, today in this blog, you’ll learn to create a new beginner-level project, Dynamic Calendar in HTML CSS & JavaScript. If you want more JavaScript projects like this, you can check out the 10 Best Beginners to Intermediate JavaScript Projects List.

As you all know, a calendar is a chart that shows the day, weeks, and months of a particular year. Calendars also help you to remind important events, such as holidays and festivals.

In my dynamic calendar, users can see the current date and day. They can also see the days of the present, past, or future month using the previous and next icons. These all are done with Vanilla JavaScript which means no external library is used to create this calendar.

If you are curious to see a live demo of this project, click here to view it. For a full video tutorial of Dynamic Calendar in JavaScript, you can watch the given YouTube video.

Video Tutorial of Dynamic Calendar in JavaScript

 
I hope you’ve watched the above video tutorial till the end and understood the basic codes and logic behind creating this calendar. If you didn’t watch it, please watch it because in the video I’ve tried my best to explain the main JavaScript lines with written comments.

If you understand the methods and logic properly, it will help you to recreate this calendar app or implement the codes of it in your projects without any confusion. Remember, if you’re already familiar with the JavaScript Date() method and have created some projects using it then the codes of this calendar won’t be difficult to understand for you.

But, if you want to get source codes or files of this calendar, you can easily copy or download them from the bottom of this blog post. If you want a blog on Date Picker in JavaScript, you can comment down and I’ll try to write a blog on it as soon as possible.

You may like this:

Dynamic Calendar in JavaScript [Source Codes]

To create a Dynamic Calendar App using HTML CSS & JavaScript, follow the given steps line by line:

  1. Create a folder. You can put any name of this folder and create the below-mentioned files inside this folder.
  2. Create a index.html file. File name must be index and its extension .html
  3. Create a style.css file. File name must be style and its extension .css
  4. Create a script.js file. File name must be script and its extension .js

Once you create these files, paste the given codes into the specified files. If you don’t want to do these then scroll down and download the source codes of this Calendar App by clicking on the given download button.

First, paste the following codes into your index.html file.

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Dynamic Calendar JavaScript | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Google Font Link for Icons -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,[email protected],100..700,0..1,-50..200">
    <script src="script.js" defer></script>
  </head>
  <body>
    <div class="wrapper">
      <header>
        <p class="current-date"></p>
        <div class="icons">
          <span id="prev" class="material-symbols-rounded">chevron_left</span>
          <span id="next" class="material-symbols-rounded">chevron_right</span>
        </div>
      </header>
      <div class="calendar">
        <ul class="weeks">
          <li>Sun</li>
          <li>Mon</li>
          <li>Tue</li>
          <li>Wed</li>
          <li>Thu</li>
          <li>Fri</li>
          <li>Sat</li>
        </ul>
        <ul class="days"></ul>
      </div>
    </div>
    
  </body>
</html>

Second, paste the following codes into your style.css file.

/* Import Google font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
body{
  display: flex;
  align-items: center;
  padding: 0 10px;
  justify-content: center;
  min-height: 100vh;
  background: #9B59B6;
}
.wrapper{
  width: 450px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 15px 40px rgba(0,0,0,0.12);
}
.wrapper header{
  display: flex;
  align-items: center;
  padding: 25px 30px 10px;
  justify-content: space-between;
}
header .icons{
  display: flex;
}
header .icons span{
  height: 38px;
  width: 38px;
  margin: 0 1px;
  cursor: pointer;
  color: #878787;
  text-align: center;
  line-height: 38px;
  font-size: 1.9rem;
  user-select: none;
  border-radius: 50%;
}
.icons span:last-child{
  margin-right: -10px;
}
header .icons span:hover{
  background: #f2f2f2;
}
header .current-date{
  font-size: 1.45rem;
  font-weight: 500;
}
.calendar{
  padding: 20px;
}
.calendar ul{
  display: flex;
  flex-wrap: wrap;
  list-style: none;
  text-align: center;
}
.calendar .days{
  margin-bottom: 20px;
}
.calendar li{
  color: #333;
  width: calc(100% / 7);
  font-size: 1.07rem;
}
.calendar .weeks li{
  font-weight: 500;
  cursor: default;
}
.calendar .days li{
  z-index: 1;
  cursor: pointer;
  position: relative;
  margin-top: 30px;
}
.days li.inactive{
  color: #aaa;
}
.days li.active{
  color: #fff;
}
.days li::before{
  position: absolute;
  content: "";
  left: 50%;
  top: 50%;
  height: 40px;
  width: 40px;
  z-index: -1;
  border-radius: 50%;
  transform: translate(-50%, -50%);
}
.days li.active::before{
  background: #9B59B6;
}
.days li:not(.active):hover::before{
  background: #f2f2f2;
}

Last, paste the following codes into your script.js file.

const daysTag = document.querySelector(".days"),
currentDate = document.querySelector(".current-date"),
prevNextIcon = document.querySelectorAll(".icons span");

// getting new date, current year and month
let date = new Date(),
currYear = date.getFullYear(),
currMonth = date.getMonth();

// storing full name of all months in array
const months = ["January", "February", "March", "April", "May", "June", "July",
              "August", "September", "October", "November", "December"];

const renderCalendar = () => {
    let firstDayofMonth = new Date(currYear, currMonth, 1).getDay(), // getting first day of month
    lastDateofMonth = new Date(currYear, currMonth + 1, 0).getDate(), // getting last date of month
    lastDayofMonth = new Date(currYear, currMonth, lastDateofMonth).getDay(), // getting last day of month
    lastDateofLastMonth = new Date(currYear, currMonth, 0).getDate(); // getting last date of previous month
    let liTag = "";

    for (let i = firstDayofMonth; i > 0; i--) { // creating li of previous month last days
        liTag += `<li class="inactive">${lastDateofLastMonth - i + 1}</li>`;
    }

    for (let i = 1; i <= lastDateofMonth; i++) { // creating li of all days of current month
        // adding active class to li if the current day, month, and year matched
        let isToday = i === date.getDate() && currMonth === new Date().getMonth() 
                     && currYear === new Date().getFullYear() ? "active" : "";
        liTag += `<li class="${isToday}">${i}</li>`;
    }

    for (let i = lastDayofMonth; i < 6; i++) { // creating li of next month first days
        liTag += `<li class="inactive">${i - lastDayofMonth + 1}</li>`
    }
    currentDate.innerText = `${months[currMonth]} ${currYear}`; // passing current mon and yr as currentDate text
    daysTag.innerHTML = liTag;
}
renderCalendar();

prevNextIcon.forEach(icon => { // getting prev and next icons
    icon.addEventListener("click", () => { // adding click event on both icons
        // if clicked icon is previous icon then decrement current month by 1 else increment it by 1
        currMonth = icon.id === "prev" ? currMonth - 1 : currMonth + 1;

        if(currMonth < 0 || currMonth > 11) { // if current month is less than 0 or greater than 11
            // creating a new date of current year & month and pass it as date value
            date = new Date(currYear, currMonth, new Date().getDate());
            currYear = date.getFullYear(); // updating current year with new date year
            currMonth = date.getMonth(); // updating current month with new date month
        } else {
            date = new Date(); // pass the current date as date value
        }
        renderCalendar(); // calling renderCalendar function
    });
});

That’s all, now you’ve successfully created a Dynamic Calendar App in HTML CSS & JavaScript. If your code doesn’t work or you’ve faced any problems, please download the source code files from the given download button. It is free and a zip file will be downloaded that contains the project folder with source code files.

 

Previous articleHow to Create Todo List App in HTML CSS & JavaScript
Next articleHow to Create Profile Card in HTML & CSS

10 COMMENTS

  1. * update message *

    there is a problem when currMonth less then 0 or currMonth greater then 11. isToday is jumping to the first of the current month.

    change
    date = new Date(currYear, currMonth);
    to
    date = new Date(currYear, currMonth, new Date().getDate());

    this will solve the problem.

    • Thanks for bringing this bug to our attention. We have made the necessary updates to the code to ensure that the current day is correctly highlighted when navigating through the calendar.

  2. there is a problem when currMonth 11. isToday is jumping to the first of the month.

    change
    date = new Date(currYear, currMonth);
    to
    date = new Date(currYear, currMonth, new Date().getDate());

    this will solve the problem.

    • You’ve to upload your project folder to the hosting. Login to hosting > go to file manager > go inside public_html and upload your project folder here. The name of your folder will be the url.

LEAVE A REPLY

Please enter your comment!
Please enter your name here