Have you ever seen a calendar on a webpage and thought to yourself, “How did they do it?” It’s natural to use plugins or even embedded Google Calendars for things like this, but in fact, making a calendar is much easier than you think, just three musketeers of HTML, CSS, and JavaScript. Let's make one together!
I've set up a demo on CodeSandbox where you can see our target.
Check out the demo First, let's determine some of the requirements for the calendar. it should:
- Displays the month grid for the specified month
- Shows dates for the previous month and the next month so that the grid is always complete
- Indicates the current date
- Show the name of the currently selected month
- Navigate to the previous month and the next month
- Allow users to return to the current month by clicking once
Oh, and we'll build it as a single page application to get calendar dates from Day.js (a super lightweight utility library).
To simplify operations, we will avoid choosing specific frameworks. For this setup, I use Parcel for package management so that I can use Babel to write code, bundle code, and manage the only dependency in the project. Check out the package.json file on CodeSandbox for more information.
Step 1: Start with basic tags and styles
Let's start with creating a basic template for your calendar. This doesn't require anything fancy. But it should also be done without using the form.
We can outline our markup as three layers, which contains:
- Calendar Title Section. This will display the currently selected month and the elements responsible for pagination between months.
- Calendar grid title section. Again, we won't use tables, but it's like a header that contains a list of days of the week.
- Calendar grid. You know, every day of the current month is represented by a square in the grid.
Let's write this in a file called index.js. This can be placed in the src folder in the project folder. We do have an index.html file in the project root directory to import our work, but the main tag will be in the JavaScript file.
document.getElementById("app").innerHTML = ` <div> <div> July 2020 </div> <div> Today > </div> <ol> <li>Mon</li> ... <li>Sun</li> </ol> <ol> <li> 1 ... 29 </li> </ol> </div> `;
Let's proceed to import this file into the index.html file located in the root directory of the project. Nothing special happened here. It is just an HTML boilerplate that contains an element that is located by our application and registered with our index.js file.
<meta charset="UTF-8"> <title>Parcel Sandbox</title> <div id="app"></div> <script src="./src/index.js"></script>
Now that we have some markers to use, let's styling a little so that we have a good visual as a start. Specifically, we will:
- Positioning elements with flexbox
- Create a calendar frame using CSS grid
- Position labels in cells
First, let's create a new styles.css file in the same src folder as index.js and put this into it:
/* ... (CSS code is the same as above) ... */
The key part of setting up a grid is:
.day-of-week, .days-grid { /* 7 equal columns for weekdays and days cells */ display: grid; grid-template-columns: repeat(7, 1fr); }
Note that both the calendar grid title and the calendar grid themselves are laid out using a CSS grid. We know there are always seven days a week, so this allows us to create seven columns proportional to each other using the repeat() function. We also declared a min-height of 100px on each calendar date to ensure rows are consistent.
We need to connect these styles with the tags, so let's add them to the top of the index.js file:
import "./styles.css";
This is a good stopping point to see what we have so far.
View the demo ### Step 2: Set the current month calendar
You may have noticed that the template currently contains only static data. The month is hardcoded as July, and the date numbers are also hardcoded. This is where Day.js comes into play. It provides all the data we need to place the date correctly in the correct date of the week using real calendar data. It allows us to get and set anything from a month start date to all date format options required to display the data.
we will:
- Get the current month
- Calculate where the date should be placed (working day)
- Calculate dates for displaying the previous month and the next month
- Combine all dates into an array
First, we need to import Day.js and delete all static HTML (selected month, weekday and date). We will do this by adding this to the import style directly above the index.js file:
import dayjs from "dayjs";
We will also rely on the Day.js plugin for help. WeekDay helps us set the first day of the week. Some people like to make Sunday the first day of the week. Others prefer Monday. Heck, in some cases it makes sense starting Friday. We will start Monday.
The weekOfYear plugin returns the numeric value of the current week of the year. There are 52 weeks in a year, so we can say that the week starting on January 1 is the first week of the year, and so on.
So here is what we add to index.js after the import statement:
const weekday = require("dayjs/plugin/weekday"); const weekOfYear = require("dayjs/plugin/weekOfYear"); dayjs.extend(weekday); dayjs.extend(weekOfYear);
Once we stripped the hardcoded calendar values, this is what we have so far in index.js:
// ... (JavaScript code is the same as above) ...
Now let's set some constants. Specifically, we want to construct an array of days of the week (i.e. Monday, Tuesday, Wednesday, etc.):
// ... (JavaScript code is the same as above) ...
Then we want to get the current year and set it in YYYY format:
// ... (JavaScript code is the same as above) ...
We want to set the current month as the starting point when loading the calendar, where M formats the month as a numeric value (e.g., January equals 1):
// ... (JavaScript code is the same as above) ...
Let's continue to fill our calendar grid titles with the days of the week. First, we get the correct element (#days-of-week), then we loop through the WEEKDAYS array, create a list item element for each item in the array, and set the name of each item:
// ... (JavaScript code is the same as above) ...
Step 3: Create a calendar grid
It's very simple, but now the real fun begins because we'll be using the calendar grid now. Let's pause and think about what we really need to do in order to do this correctly.
First, we want the date numbers to fall in the correct working day column. For example, July 1, 2020 is Wednesday. This is where the date number should start.
If the first day of a month is Wednesday, then this means that there will be available grid items on Monday and Tuesday of the first week. The last day of the month is July 31, Friday. This means Saturday and Sunday of the last week will be empty. We want to populate these dates with trailing dates and leading dates for the previous month and the next month so that the calendar grid is always complete.
Create the date of the current month
To add the date of the current month to the grid, we need to know how many days there are in the current month. We can use the daysInMonth method provided by Day.js to get it. Let's create a helper method for this.
// ... (JavaScript code is the same as above) ...
When we know this, we create an empty array of length equals the number of days in the current month. We then map() the array and create a date object for each array. The objects we create have arbitrary structure, so you can add additional properties if you want.
In this example, we need a date property that will be used to check if a specific date is the current date. We will also return a dayOfMonth property that acts as a label (e.g. 1, 2, 3, etc.). isCurrentMonth Checks whether the date is within or outside the current month. If it is outside the current month, we will style it so people know they are outside the range of the current month.
// ... (JavaScript code is the same as above) ...
Add the date of the previous month to the calendar grid
To get the date of the previous month to show in the current month, we need to check what day of the week the first day of the selected month is. This is where we can use the WeekDay plugin for Day.js. Let's create a helper method for this.
// ... (JavaScript code is the same as above) ...
Then, based on this, we need to check which day the last Monday of the previous month was. We need this value to know how many days of the previous month should be displayed in the current month view. We can get it by subtracting the value of the working day from the first day of the current month. For example, if the first day of a month is Wednesday, we need to subtract 3 days to get the last Monday of the previous month. With this value, we can create an array of date objects starting from the last Monday of the previous month and all the way to the last day of that month.
// ... (JavaScript code is the same as above) ...
Add the next month's date to the calendar grid
Now, let's turn to calculate which dates we need to get from the next month to fill the grid of the current month. Fortunately, we can use the same helper method we just created for the previous month's calculations. The difference is that we will calculate how many days should be displayed in the next month by subtracting that working day value from 7.
So, for example, if the last day of a month is Saturday, we need to subtract 1 day from 7 to construct the required date array from the next month (Sunday).
// ... (JavaScript code is the same as above) ...
OK, we know how to create all the required days, let's use the method we just created and then merge all the days into a single array containing all the days we want to display in the current month, including the padding dates for the previous month and the next month.
// ... (JavaScript code is the same as above) ...
Here is everything we put together in index.js:
// ... (JavaScript code is the same as above) ...
View Demo### Step 4: Show Calendar Date
OK, so we have the basic markers for the calendar, we need to display data for the current month date, plus the dates of the previous month and the next month to fill in the empty grid items. Now we need to attach the date to the calendar!
We already have a container for a calendar grid #calendar-days. Let's get the element.
// ... (JavaScript code is the same as above) ...
Now let's create a function that attaches dates to calendar view.
// ... (JavaScript code is the same as above) ...
Note that we are checking dates from the previous month and the next month so that we can add a class to distinguish them from the dates of the current month:
// ... (CSS code is the same as above) ...
That's it! Our calendar should now be displayed the way we want it to be.
View Demo### Step 5: Select the current month
What we have so far is pretty good, but we want users to be able to page the month forward and backward, starting with the current month. We already have most of the logic, so what we really need to do is add a click listener to the paging button that reruns the date calculation and repaints the calendar with updated data.
Before we start, let's define the date variables for the current month, the previous month, and the next month so that we can reference them throughout the code.
// ... (JavaScript code is the same as above) ...
Now let's create a method that will be responsible for recalculating the calendar date and re-rendering the calendar when paging to another month. We will call the function createCalendar. This method will accept two properties—year and month—and based on this, the calendar will be rerendered with new data without reloading the page.
This method replaces the title content to always display the selected month label.
// ... (JavaScript code is the same as above) ...
It will then get the calendar date container and delete all existing dates.
// ... (JavaScript code is the same as above) ...
After clearing the calendar, it will calculate the new date that should be displayed using the method we created earlier.
// ... (JavaScript code is the same as above) ...
Finally, it will attach a date element to each day.
// ... (JavaScript code is the same as above) ...
There is also a logical part missing: a removeAllDayElements method that clears an existing calendar. This method takes the first calendar date element, deletes it, and replaces it with another element. From there, it will loop the logic until all elements are deleted.
// ... (JavaScript code is the same as above) ...
Now, when we want to change the month, we can reuse that logic. Recall the first step, when we created a static template for the component. We added these elements:
// ... (HTML code is the same as above) ...
These are the controls for pagination between months. To change it, we need to store the currently selected month. Let's create a variable that tracks what it is and set its initial value to this month.
// ... (JavaScript code is the same as above) ...
Now, in order for the selector to work, we need some JavaScript. To make it easier to read, we will create another method called initMonthSelectors and leave the logic there. This method adds an event listener to the selector element. It listens for click events and updates the value of selectedMonth to the name of the newly selected month, and then runs the createCalendar method with the correct year and month values.
// ... (JavaScript code is the same as above) ...
That's it! Our calendar is ready. While this is good, it would be even better if we could mark the current date so that it stands out from the rest. This shouldn't be difficult. We are already setting a date style outside of the current month, so let's do something similar.
We will create a variable set to today:
// ... (JavaScript code is the same as above) ...
Then, in the appendDay method, when we apply a class with a date outside the current month, we have to add another check to see if the element is today's date. If so, we will add a class to the element:
// ... (JavaScript code is the same as above) ...
Now we can set the style!
// ... (CSS code is the same as above) ...
Look, we're done! Check out the final demo to see a combination of everything.
View the demo
The above is the detailed content of How to Make a Monthly Calendar With Real Data. For more information, please follow other related articles on the PHP Chinese website!

GooFonts is a side project signed by a developer-wife and a designer-husband, both of them big fans of typography. We’ve been tagging Google

Pavithra Kodmad asked people for recommendations on what they thought were some of the most timeless articles about web development that have changed their

Learning how to build GraphQL APIs can be quite challenging. But you can learn how to use GraphQL APIs in 10 minutes! And it so happens I've got the perfect

When a component lives in an environment where the data queries populating it live nearby, there is a pretty direct line between the visual component and the

Here's some legit CSS trickery from yuanchuan. There is this CSS property offset-path. Once upon a time, it was called motion-path and then it was renamed. I

Miriam Suzanne explains in a Mozilla Developer video on the subject.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version