search
HomeWeb Front-endFront-end Q&AHow to make a monthly calendar with JavaScript

Introduction to how to make a monthly calendar using JavaScript

JavaScript is a programming language used for web development. It is a dynamic scripting language that is usually used for client-side web development. In this article, we will introduce how to use JavaScript to create a simple monthly calendar on a web page.

Requirements:

Before making the monthly calendar, we need the following files:

1. An HTML file for building a web interface

2.CSS File, used to apply styles to HTML files

3. JavaScript file, used to add the functionality of a monthly calendar

Next, let’s create a monthly calendar from scratch.

Create HTML file

First create an HTML file, we can write it from scratch, or use a template and save it as a .html file. Add the following code to the file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>月历</title>
</head>
<body>
    <h1 id="月历">月历</h1>
    <table>
        <thead>
            <tr>
                <th>星期日</th>
                <th>星期一</th>
                <th>星期二</th>
                <th>星期三</th>
                <th>星期四</th>
                <th>星期五</th>
                <th>星期六</th>
            </tr>
        </thead>
        <tbody id="calendarBody">
        </tbody>
    </table>

    <script type="text/javascript" src="calendar.js"></script>
</body>
</html>

In this HTML file, we define an h1 tag titled "Month Calendar" and add an attribute with the id "currentMonth" within the tag. This attribute Will be used to display the current month in JavaScript code. We also use a table tag to display the calendar. There are seven columns in this table, corresponding to the seven-day week. A tbody tag is used to generate the monthly calendar table in JavaScript code, and we also added a script tag that contains our JavaScript file that will be used to generate the monthly calendar for the page.

We can also add some CSS styles to this HTML file to beautify the page:

table {
    border-collapse: collapse;
    width: 100%;
}

th, td {
    border: 1px solid black;
    text-align: center;
}

th {
    height: 25px;
    background-color: #cccccc;
}

td {
    height: 50px;
}

These styles will add some basic styles to the table, th and td elements of the page.

Create JavaScript file

Now, we need to create a JavaScript file to add a monthly calendar function to the page. We save this file as "calendar.js".

In this file, we define a function to create a monthly calendar table:

function createCalendar(month, year) {
    var weekdays = ["日","一","二","三","四","五","六"];
    var calendarBody = document.getElementById("calendarBody");
    var daysInMonth = new Date(year, month+1, 0).getDate();
    var date = new Date(year, month, 1);
    var row = document.createElement("tr");

    for (var i = 0; i < weekdays.length; i++) {
        var cell = document.createElement("th");
        cell.innerText = weekdays[i];
        row.appendChild(cell);
    }

    calendarBody.appendChild(row);

    for (var i = 1; i <= daysInMonth; i++) {
        var newDate = new Date(year, month, i);
        var dayOfWeek = newDate.getDay();
        if (dayOfWeek === 0) {
            row = document.createElement("tr");
            calendarBody.appendChild(row);
        }
        var cell = document.createElement("td");
        cell.innerText = i;
        row.appendChild(cell);
    }
}

In this function, we first define an array to store the names of Sunday to Saturday . We also obtained the tbody element through the document.getElementById method, and obtained the number of days in the current month and the date of the first day. Next, we created a table header row and added a header cell containing the name of the day of the week in this row. Then, we add date cells row by row, and if a date cell encounters a Sunday, we create a new row.

Next, we need to add a function to update the current month of the monthly calendar:

function updateCalendar() {
    var currentMonth = document.getElementById("currentMonth");
    var currentDate = new Date();
    var month = currentDate.getMonth();
    var year = currentDate.getFullYear();
    currentMonth.innerText = year + "年" + (month+1) + "月";
    createCalendar(month, year);
}

In this function, we first use the document.getElementById method to get the h1 element of the current month, and then create a Date object to get the current date, month, year, and set the innerText attribute of the h1 element.

Finally, we need to call the updateCalendar function to generate the monthly calendar:

window.onload = function() {
    updateCalendar();
}

This code will call the updateCalendar function after the page is fully loaded.

At this point, we have completed the production of the monthly calendar. Now we can open this HTML file in the browser and see the generated monthly calendar.

The above is the detailed content of How to make a monthly calendar with JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is useEffect? How do you use it to perform side effects?What is useEffect? How do you use it to perform side effects?Mar 19, 2025 pm 03:58 PM

The article discusses useEffect in React, a hook for managing side effects like data fetching and DOM manipulation in functional components. It explains usage, common side effects, and cleanup to prevent issues like memory leaks.

Explain the concept of lazy loading.Explain the concept of lazy loading.Mar 13, 2025 pm 07:47 PM

Lazy loading delays loading of content until needed, improving web performance and user experience by reducing initial load times and server load.

What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code?What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code?Mar 18, 2025 pm 01:44 PM

Higher-order functions in JavaScript enhance code conciseness, reusability, modularity, and performance through abstraction, common patterns, and optimization techniques.

How does currying work in JavaScript, and what are its benefits?How does currying work in JavaScript, and what are its benefits?Mar 18, 2025 pm 01:45 PM

The article discusses currying in JavaScript, a technique transforming multi-argument functions into single-argument function sequences. It explores currying's implementation, benefits like partial application, and practical uses, enhancing code read

How does the React reconciliation algorithm work?How does the React reconciliation algorithm work?Mar 18, 2025 pm 01:58 PM

The article explains React's reconciliation algorithm, which efficiently updates the DOM by comparing Virtual DOM trees. It discusses performance benefits, optimization techniques, and impacts on user experience.Character count: 159

How do you prevent default behavior in event handlers?How do you prevent default behavior in event handlers?Mar 19, 2025 pm 04:10 PM

Article discusses preventing default behavior in event handlers using preventDefault() method, its benefits like enhanced user experience, and potential issues like accessibility concerns.

What is useContext? How do you use it to share state between components?What is useContext? How do you use it to share state between components?Mar 19, 2025 pm 03:59 PM

The article explains useContext in React, which simplifies state management by avoiding prop drilling. It discusses benefits like centralized state and performance improvements through reduced re-renders.

What are the advantages and disadvantages of controlled and uncontrolled components?What are the advantages and disadvantages of controlled and uncontrolled components?Mar 19, 2025 pm 04:16 PM

The article discusses the advantages and disadvantages of controlled and uncontrolled components in React, focusing on aspects like predictability, performance, and use cases. It advises on factors to consider when choosing between them.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)