My calendar was functioning properly earlier. However, it has started to skip months and only display those with 31 days.
For example: if the current month is May, the next month should be June. But instead, it repeats May and then jumps to July (which has 31 days).
let nav = 0;
const calendar = document.getElementById("calendar");
const weekdays = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
function load() {
const dt = new Date();
if (nav !== 0) {
dt.setMonth(new Date().getMonth() + nav);
}
const day = dt.getDate();
const month = dt.getMonth();
const year = dt.getFullYear();
const firstDayOfMonth = new Date(year, month, 1);
const daysInMonth = new Date(year, month + 1, 0).getDate();
const dateString = firstDayOfMonth.toLocaleDateString("en-us", {
weekday: "long",
year: "numeric",
month: "numeric",
day: "numeric",
});
const paddingDays = weekdays.indexOf(dateString.split(", ")[0]);
document.getElementById("monthDisplay").innerText =
dt.toLocaleDateString("pt-br", {
month: "long"
}).toUpperCase() +
" " +
year;
calendar.innerHTML = "";
for (let i = 1; i <= paddingDays + daysInMonth; i++) {
const daySquare = document.createElement("div");
daySquare.classList.add("day");
if (i > paddingDays) {
daySquare.innerText = i - paddingDays;
daySquare.addEventListener("click", () => console.log("click"));
} else {
daySquare.classList.add("padding");
}
calendar.appendChild(daySquare);
}
}
function initButtons() {
document.getElementById("nextButton").addEventListener("click", () => {
nav++;
load();
});
document.getElementById("backButton").addEventListener("click", () => {
nav--;
load();
});
}
initButtons();
load();
<div id="header">
<button id="backButton">Back</button>
<div id="monthDisplay"></div>
<button id="nextButton">Next</button>
</div>
<div id="weekdays">
<div>Domingo</div>
<div>Segunda</div>
<div>Terça</div>
<div>Quarta</div>
<div>Quinta</div>
<div>Sexta</div>
<div>Sabado</div>
</div>
<div id="calendar"></div>