Creating a dynamic calendar is a great way to enhance your web development skills and can be a valuable addition to any website or application. In this tutorial, we'll walk through building a functional calendar from scratch using HTML, CSS, and JavaScript. By the end, you'll have a calendar that displays the current month and allows users to navigate between months.
Table of Contents
- Project Overview
- Setting Up the Project
- Creating the HTML Structure
- Styling the Calendar with CSS
- Adding Functionality with JavaScript
- Enhancements and Final Touches
- Conclusion
Project Overview
We will create a calendar that:
- Displays the current month and year.
- Shows all the days of the current month.
- Allows users to navigate to previous and next months.
Technologies Used:
- HTML: For the structure of the calendar.
- CSS: For styling the calendar.
- JavaScript: For dynamic rendering and interactivity.
Setting Up the Project
First, let's set up our project directory with the following files:
-
index.html
: The main HTML file. -
styles.css
: The CSS file for styling. -
script.js
: The JavaScript file for functionality.
Directory Structure
/calendar-project
|-- index.html
|-- styles.css
|-- script.js
Creating the HTML Structure
Open index.html
and set up the basic HTML template.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dynamic Calendar</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="calendar">
<div class="calendar-header">
<button id="prev-month">‹</button>
<div id="month-year"></div>
<button id="next-month">›</button>
</div>
<div class="calendar-body">
<div class="calendar-weekdays">
<!-- Weekday Names -->
</div>
<div class="calendar-dates">
<!-- Dates will be populated here -->
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Explanation
-
Calendar Container: The main wrapper with the class
calendar
. - Header: Contains navigation buttons and displays the current month and year.
- Weekdays: A row displaying the names of the weekdays.
- Dates: The grid where all the dates will be populated dynamically.
Styling the Calendar with CSS
Open styles.css
and add the following styles.
body {
font-family: Arial, sans-serif;
background-color: #f4f6f9;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.calendar {
width: 350px;
background-color: #fff;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.calendar-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
}
.calendar-header button {
background-color: transparent;
border: none;
font-size: 1.5em;
cursor: pointer;
}
#month-year {
font-size: 1.2em;
font-weight: bold;
}
.calendar-weekdays, .calendar-dates {
display: grid;
grid-template-columns: repeat(7, 1fr);
}
.calendar-weekdays div, .calendar-dates div {
text-align: center;
padding: 10px;
}
.calendar-weekdays {
background-color: #eaeef3;
}
.calendar-weekdays div {
font-weight: bold;
}
.calendar-dates div {
border-bottom: 1px solid #eaeef3;
cursor: pointer;
}
.calendar-dates div:hover {
background-color: #f1f1f1;
}
Explanation
- Layout: The calendar is centered on the page with a fixed width.
- Header: Styles for the navigation buttons and the month-year display.
- Grid System: Using CSS Grid to create a 7-column layout for weekdays and dates.
- Interactivity: Hover effects on the dates for better user experience.
Adding Functionality with JavaScript
Now, let's make our calendar dynamic. Open script.js
and start coding.
Initializing Variables
const calendarDates = document.querySelector('.calendar-dates');
const monthYear = document.getElementById('month-year');
const prevMonthBtn = document.getElementById('prev-month');
const nextMonthBtn = document.getElementById('next-month');
let currentDate = new Date();
let currentMonth = currentDate.getMonth();
let currentYear = currentDate.getFullYear();
const months = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
];
Rendering the Calendar
Function to Render the Calendar
function renderCalendar(month, year) {
calendarDates.innerHTML = '';
monthYear.textContent = `${months[month]} ${year}`;
// Get the first day of the month
const firstDay = new Date(year, month, 1).getDay();
// Get the number of days in the month
const daysInMonth = new Date(year, month + 1, 0).getDate();
// Create blanks for days of the week before the first day
for (let i = 0; i < firstDay; i++) {
const blank = document.createElement('div');
calendarDates.appendChild(blank);
}
// Populate the days
for (let i = 1; i <= daysInMonth; i++) {
const day = document.createElement('div');
day.textContent = i;
calendarDates.appendChild(day);
}
}
Initial Render
renderCalendar(currentMonth, currentYear);
Navigating Between Months
Event Listeners for Navigation Buttons
prevMonthBtn.addEventListener('click', () => {
currentMonth--;
if (currentMonth < 0) {
currentMonth = 11;
currentYear--;
}
renderCalendar(currentMonth, currentYear);
});
nextMonthBtn.addEventListener('click', () => {
currentMonth++;
if (currentMonth > 11) {
currentMonth = 0;
currentYear++;
}
renderCalendar(currentMonth, currentYear);
});
Displaying Weekday Names
Back in index.html
, within the .calendar-weekdays
div, add the weekday names.
<div class="calendar-weekdays">
<div>Sun</div>
<div>Mon</div>
<div>Tue</div>
<div>Wed</div>
<div>Thu</div>
<div>Fri</div>
<div>Sat</div>
</div>
Enhancements and Final Touches
Highlighting the Current Date
Modify the renderCalendar
function to highlight the current date.
function renderCalendar(month, year) {
// ... existing code ...
// Get today's date
const today = new Date();
// Populate the days
for (let i = 1; i <= daysInMonth; i++) {
const day = document.createElement('div');
day.textContent = i;
// Highlight today's date
if (
i === today.getDate() &&
year === today.getFullYear() &&
month === today.getMonth()
) {
day.classList.add('current-date');
}
calendarDates.appendChild(day);
}
}
Add the following CSS to styles.css
:
.current-date {
background-color: #007bff;
color: #fff;
border-radius: 50%;
}
Adding Click Events to Dates
Suppose we want to alert the date when a user clicks on it.
calendarDates.addEventListener('click', (e) => {
if (e.target.textContent !== '') {
alert(`You clicked on ${e.target.textContent} ${months[currentMonth]} ${currentYear}`);
}
});
Responsive Design
Adjust the calendar width for smaller screens.
@media (max-width: 400px) {
.calendar {
width: 100%;
margin: 0 10px;
}
}
Conclusion
Congratulations! You've built a dynamic and interactive calendar using HTML, CSS, and JavaScript. This project covers important concepts such as DOM manipulation, event handling, and working with dates in JavaScript.
Key Takeaways:
- DOM Manipulation: Creating and appending elements dynamically.
-
Date Object: Using JavaScript's
Date
object to handle dates. - Event Handling: Adding interactivity with event listeners.
Possible Extensions:
- Allow users to select dates for scheduling events.
- Integrate with an API to display holidays.
- Add a feature to switch between different calendar views (e.g., yearly, weekly).
Follow me on YouTube for more tutorials
Top comments (0)