How to create a calendar in JavaScript with CSS?

Are you wondering how to create or add a dynamic calendar in your JavaScript code?

In this article, we will show you the process of building a calendar with HTML, CSS, and JavaScript.

The calendar will show the present month and year and grant users the ability to move back and forth between preceding and succeeding months.

javascript calendar

Aside from that, users will have the option to directly access any desired month and year. Also, the calendar will emphasize the current date.

How to Create Dynamic Calendar in JavaScript

Here’s a simple way to create a dynamic calendar using JavaScript and CSS:

HTML

First, you’ll need to create an HTML file with a div element to hold the calendar.

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Calendar</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="calendar">
    <div class="header">
      <!-- Previous and Next buttons -->
      <button id="prev">Previous</button>
      <h1 id="month-year"></h1>
      <button id="next">Next</button>
    </div>
    <div class="weekdays">
      <!-- Weekday names -->
      <span>Sun</span>
      <span>Mon</span>
      <span>Tue</span>
      <span>Wed</span>
      <span>Thu</span>
      <span>Fri</span>
      <span>Sat</span>
    </div>
    <div class="days" id="calendar-days"></div>
  </div>
  <div class="event-form" id="event-form" style="display: none;">
    <!-- Event input and Save button -->
    <input type="text" id="event-input" placeholder="Enter your event">
    <button id="save-event">Save</button>
  </div>
  <script src="script.js"></script>
</body>
</html>

Script.js

Next, you’ll need to create a JavaScript file and link it to your HTML file. In this file, you can create a function that generates the calendar.

This function should take in a date as an argument and use it to determine the month and year to display.

// JavaScript
document.addEventListener("DOMContentLoaded", function () {
  const prevBtn = document.getElementById("prev");
  const nextBtn = document.getElementById("next");
  const monthYearElem = document.getElementById("month-year");
  const calendarDaysElem = document.getElementById("calendar-days");
  const eventForm = document.getElementById("event-form");
  const eventInput = document.getElementById("event-input");
  const saveEventBtn = document.getElementById("save-event");

  let currentDate = new Date();
  let selectedDate = null;
  let events = {}; // Object to store events { '2023-08': { '2': ['event1', 'event2'], '7': ['event3'] }, ... }

  function renderCalendar() {
    const firstDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
    const lastDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);
    const prevMonthLastDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 0);

    const firstDayOfWeek = firstDayOfMonth.getDay();
    const lastDayOfWeek = lastDayOfMonth.getDay();

    const days = [];
    for (let i = prevMonthLastDay.getDate() - firstDayOfWeek + 1; i <= prevMonthLastDay.getDate(); i++) {
      days.push(`<span class="prev-month">${i}</span>`);
    }
    for (let i = 1; i <= lastDayOfMonth.getDate(); i++) {
      const isToday = currentDate.toDateString() === new Date(currentDate.getFullYear(), currentDate.getMonth(), i).toDateString();
      const eventsForDate = events[`${currentDate.getFullYear()}-${currentDate.getMonth() + 1}`]?.[i];
      days.push(`<span class="${isToday ? 'today' : ''}" data-date="${i}">${i}${eventsForDate ? '<div class="events">' + eventsForDate.join('<br>') + '</div>' : ''}</span>`);
    }
    for (let i = 1; i <= 6 - lastDayOfWeek; i++) {
      days.push(`<span class="next-month">${i}</span>`);
    }

    calendarDaysElem.innerHTML = days.join("");
    monthYearElem.textContent = `${currentDate.toLocaleString("default", { month: "long" })} ${currentDate.getFullYear()}`;
  }

  function prevMonth() {
    currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 1);
    renderCalendar();
  }

  function nextMonth() {
    currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1);
    renderCalendar();
  }

  function highlightSelectedDate(event) {
    const selectedDay = event.target;
    const dateAttribute = selectedDay.dataset.date;

    if (dateAttribute) {
      const allDays = document.querySelectorAll('.days span');
      allDays.forEach(day => day.classList.remove('selected'));
      selectedDay.classList.add('selected');
      selectedDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), dateAttribute);

      // Show the event form when a date is selected
      eventForm.style.display = "block";
    }
  }

  function saveEvent() {
    if (selectedDate && eventInput.value.trim() !== "") {
      const dateKey = `${selectedDate.getFullYear()}-${selectedDate.getMonth() + 1}`;
      if (!events[dateKey]) {
        events[dateKey] = {};
      }
      const date = selectedDate.getDate().toString();
      if (!events[dateKey][date]) {
        events[dateKey][date] = [];
      }
      events[dateKey][date].push(eventInput.value.trim());

      eventInput.value = "";
      eventForm.style.display = "none";
      renderCalendar(); // Refresh the calendar to display the updated events
    }
  }

  prevBtn.addEventListener("click", prevMonth);
  nextBtn.addEventListener("click", nextMonth);
  calendarDaysElem.addEventListener("click", highlightSelectedDate);
  saveEventBtn.addEventListener("click", saveEvent);

  renderCalendar();
});

CSS

Lastly, you can use CSS to style your calendar. You can add styles to your HTML file using a style tag or by linking to an external CSS file.

Here’s an example of some simple styles you may use:

/* CSS */
body {
  font-family: Arial, sans-serif;
  text-align: center;
}

.calendar {
  max-width: 400px; /* Adjust the max-width as needed */
  margin: 0 auto;
  border: 1px solid #005799;
  padding: 10px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  margin-bottom: 10px;
}

.weekdays span {
  padding: 5px;
  font-weight: bold;
}

.days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-template-rows: 1fr; /* Set only 1 row */
}

.days span {
  display: block;
  padding: 5px;
  text-align: center;
  cursor: pointer;
  min-height: 50px; /* Set a minimum height for each day cell */
}

.days span.today {
  background-color: #007bff;
  color: white;
}

.days span.selected {
  background-color: #ff004c;
  color: rgb(236, 135, 135);
}

.days span:not(.today):hover {
  background-color: #f2f2f2;
}

.event-form {
  padding: 10px;
}
.prev-month, .next-month {
  color: #999;
  opacity: 0.5;
}

Here’s the final output:

Conclusion

In conclusion, we have demonstrated a straightforward method to create a dynamic calendar using HTML, CSS, and JavaScript. 

This calendar displays the current month and year and allows users to navigate back and forth between preceding and succeeding months. Additionally, users can directly access any desired month and year.

The calendar also highlights the current date for easy identification.

By following the steps outlined in this article, you can build a functional and visually appealing calendar that can be integrated into your JavaScript projects.

Customization options are plentiful, allowing you to tailor the calendar’s appearance and functionality to suit your specific needs.

Incorporating a dynamic calendar into web applications can be a great benefit for users in effectively managing their events, schedules, and appointments.

 We are hoping that this article provides you with enough information that helps you understand how to create a calendar in JavaScript. 

You can also check out the following article:

Thank you for reading itsourcecoders 😊.

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.
Caren Bautista

Technical Writer at PIES IT Solution

Responsible for crafting clear, well-structured, and beginner-friendly content across the platform. Handles the writing, proofreading, and editorial review of tutorials, guides, and documentation to ensure every article is accurate, readable, and easy to follow.

Expertise: Technical Writing · Content Creation · Documentation · Editorial Writing · JavaScript · TypeScript · Python · Python Errors · HTTP Errors · MS Excel  · View all posts by Caren Bautista →

Leave a Comment