I need help with my calendar that only displays months with 31 days! Can anyone assist me, please?

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>

Answer №1

The issue arises when the script is executed on March 31st.

For instance, if you initialize a new Date object like this:

  const dt = new Date();

the variable dt will be set to March 31st. Subsequently, when you perform the following operation:

    dt.setMonth(new Date().getMonth() + nav);

In the case where nav == 1, it would try to return April 31st. However, since there is no 31st day in April, it automatically switches to May 1st.

If your intention is to navigate through months accurately, it's advisable to use the first day of the month as your reference point instead of the current date:

  const today = new Date();
  const dt = new Date(today.getFullYear(), today.getMonth());

The day variable does not play a role in your code, so you can eliminate the line:

  const day = dt.getDate();

However, if you require the current day of the month, you can access that information from today():

  const day = today.getDate();

Answer №2

It's a bit tricky to pinpoint the exact reason behind the unexpected behavior of your code with

dt.setMonth(new Date().getMonth() + nav)
. When checking the output of dt in the console, it seemed to alternate between the first day of the month, the last day, and occasionally skipping over a month. To address this issue, I made some changes by eliminating the nav variable, transforming dt, day, month, and year into global variables, and incorporating adjustments within the click event listeners to increment the year and month appropriately. While these modifications answer your query, they may not align precisely with what you were seeking. If additional insight or specific constraints exist, please share them in the comments so we can assist further. Thank you.

//let nav = 0;
let dt = new Date();
let day = dt.getDate();
let month = dt.getMonth();
let year = dt.getYear() + 1900;

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()-1;
  // const month = dt.getMonth();
  // const year = dt.getFullYear();
  // dt.setDate(day);
  dt.setMonth(month);
  dt.setYear(year);

  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]);

  const monthName = dt.toLocaleString('pt-br', {month: 'long'});

  document.getElementById("monthDisplay").innerText =
    monthName.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++;
    if(month == 11){
      dt.setMonth(month = 0);
      year++;
    }else{
      dt.setMonth(++month);
    }
    load();
  });

  document.getElementById("backButton").addEventListener("click", () => {
    // nav--;
    if(month == 0){
      dt.setMonth(month = 11);
      year--;
    }else{
      dt.setMonth(--month);
    }
    load();
  });
}

initButtons();
load();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An error occurs with Three JS when trying to access a S3 Bucket used as a CDN due to Cross Origin

function displayItem() { startScene(); THREE.ImageUtils.crossOrigin = "anonymous"; var mtlLoader = new THREE.MTLLoader(); mtlLoader.setTexturePath('https://cdn.rubyrealms.com/textures/'); mtlLoader.setPath('https://cdn.ru ...

Tips for making radio button selection mandatory in an HTML5 form

How can I require a user to select one radio button in an HTML 5 form before submitting it? I attempted to use the required attribute, but since there is no radio button group, how can I apply this requirement? <form action="/Home/Sendtitle" method=" ...

Is it possible to determine the search query if the search term appears within the website URL?

I'm trying to figure out which action url and name term to use when the search term is located in the middle of the URL. For instance, the HTML code below enables me to type text and upon pressing enter or the button, it redirects me to the website w ...

The keyframes alternate feature in CSS3 animation is not triggering

I'm attempting to create a simple animation using rotations and keyframes that triggers when the user hovers over an element. The issue I'm facing is that once the user stops hovering over the element, the animation does not reverse. You can see ...

Implementing Vue modal within a Laravel 5.2 foreach loop

I am facing a challenge with my Laravel blade template that uses a foreach loop to create a table with data. Each row has a link that triggers a modal when clicked. However, the issue is that clicking on any link activates the modal for every row instead o ...

How come my CheerpJ web page displays the loading screen but fails to function properly?

I have recently started using CheerpJ and went through the getting started tutorial. Despite following all the steps, I encountered an issue where my webpage only displayed the CheerpJ loading screen (the rotating circle) without running my app. Can anyo ...

How can I display the most recent offcanvas opening at the top of the page?

The issue I'm facing is related to the offcanvas3 opening behind offcanvas2. It appears like this: $("#open-offcanvas2").on("click", function(){ $("#offcanvas2").offcanvas("show") }) $("#open-offcanvas1").on("click", function(){ $("#offcanvas1" ...

"Eliminate any inline styling from a string element with the power of JavaScript/j

If I have the following string: let sentence = '<h1 style="lots of class"> </h1><h2> <p style="bunch of class"> </p> <p style="bunch of class"> </p></h2>'; This string contains multiple elements a ...

Can we create a process that automatically transforms any integer field into a hashed string?

Is there a non-hacky way to hash all IDs before returning to the user? I have explored the documentation extensively but haven't found a solution that covers all scenarios. I am working with Postgres and Prisma ORM, managing multiple models with rela ...

Leveraging the power of jQuery and vanilla JavaScript to create a pop-up print window for a Div element within a CMS platform that does not support media query stylesheets

I have been grappling with this particular issue for weeks now, seeking guidance from previous inquiries here. Yet, despite the helpful hints, I am still struggling to find a viable solution. My website features a scrolling sidebar measuring approximately ...

Utilizing Phantom Js with Apache server

After creating a JavaScript app, I realized the importance of making it SEO friendly. I am curious if anyone has experience setting up a crawlable webpage on Apache using Backbone.js (potentially with assistance from PHP and .htaccess files, or with Phant ...

What is causing the inconsistency in the widths of these HTML elements?

I recently created multiple div elements with a uniform width of 5px. Here is the CSS code I used: div { background-color: black; width: 5px; height: 100px; display: inline-block; } To my surprise, despite setting the same width for all divs, som ...

Subsequent line in hta/html

I have been attempting to achieve the following output: Line 1 Line 2 Line 3 My attempts so far have included: <p>Line 1 Line 2 Line 3</p> Unfortunately, this results in: Line 1 Line 2 Line 3 I also tried the following method: <p>L ...

Adding link styles to the <a> tag in Bootstrap 4 Alpha 3: A simple guide

The following code is quite simple: <a>This is a link</a> In a demonstration of Bootstrap 4 Alpha 2 here, the link appears blue. When you hover over it, it turns dark blue. However, in a demonstration of Bootstrap 4 Alpha 3 here, it displays ...

Enhance your scheduling capabilities with FullCalendar2's customizable minTime and maxTime settings for each

Can each weekday have different minTime and maxTime in fullcalendar (the hours on the left side)? For example: Monday: 08:00 - 18:00 Tuesday: 08:00 - 18:00 Wednesday: 10:00 - 19:00 Thursday: 13:00 - 20:00 ... The default setting in fullcalendar appl ...

How do I ensure a single row in my table constantly remains at the bottom?

I am currently working on developing a MUI table that shows rows, with the last row displaying the total number of colors. The challenge I am facing is ensuring that the last row always stays at the bottom when there are no results in the table. I have att ...

Combining Two JSON Arrays Featuring Unique Keys

I have two JSON arrays with slightly different keys. The first JSON array contains the keys id, name, and title. The second JSON array includes id, title, forename, name, and company. I am wondering if it's possible to merge these two arrays so th ...

I am interested in rotating the yAxes scaleLabel in Angular using Chart.js

I have a vertical chart that I want to rotate horizontally. Unfortunately, there are no maxRotation and minRotation parameters for the yAxes, so I'm unsure of how to achieve this rotation. Although I found a similar question, I struggled to implement ...

Efficiently generating and managing numerous toggle buttons in Reactjs with Material-ui ToggleButtons

Currently, I am exploring the idea of designing a sidebar that incorporates a variable number of toggle buttons generated from an object containing keys and values. However, I am encountering difficulties in utilizing the "key" value to adjust the corres ...

Green and red values hovering within the keyframe

Currently, I'm facing a dilemma involving keyframes. I have a table populated with values retrieved from a JSON fetch and need to implement a hover effect where values less than 5 show in red, while those equal to or greater than 5 appear in green. Be ...