Information vanishes as the element undergoes modifications

I am currently working with a JSON file that contains information about various events, which I am displaying on a calendar.

Whenever an event is scheduled for a particular day, I dynamically add a div element to indicate the presence of an event on the calendar.

The calendar plugin I have integrated is called VanillaCalendar. During the DOM load, I initialize the calendar and implement a function to iterate through the JSON data and assign events to corresponding days on the calendar.

This snippet showcases my loop logic for assigning events to specific days:

        for (const {month, days} of eventData) {
          for (const {day, events} of days) {
              const key = day.split('-').map(p => p.padStart(2, '0')).join('-');
              let dayElement = document.querySelector(`[data-calendar-day="${key}"]`);
              let eventWrapper = document.createElement("div");
              eventWrapper.classList.add("event-wrapper");
              dayElement.append(eventWrapper);
              for (const {title, category} of events) {
                  let singleEvent = document.createElement("div");
                  singleEvent.classList.add("event", category);
                  eventWrapper.append(singleEvent);
              }
          }

To view a live demo, please visit my CodePen showcase.

However, one issue I am encountering is that when switching months, the events fail to populate on the calendar.

In case you explore my CodePen and switch the month, you will notice that events from February or any other month are not displayed despite having relevant data in the JSON file.

If anyone can provide insights on how I could display events even across different months, I would greatly appreciate it.

I attempted utilizing the VanillaCalendar clickMonth action to trigger my function upon clicking the month arrows. However, incorporating a delay like below did not resolve the issue of populating events for February or other months:

clickArrow(e, self) {
      setTimeout(assignEventsToCalendar, 3000);
}

Answer №1

Here are three key updates:

  • We now assign event listeners via the options object, as outlined in the documentation. This allows us to assign a named function rather than creating a new one, resulting in a slightly different assignment method.

  • We removed a redundant loop over the eventData.

  • Event flair is now only applied if the day exists on the calendar. We simply check if the element exists before proceeding with applying flair.

document.addEventListener("DOMContentLoaded", function() {   
    console.log(data.month);
    var currentDate = new Date().toISOString().slice(0, 10);

    var options = {
        date: {
            min: "1920-01-01",
            max: "2038-12-31"
        },
        settings: {
            range: {
                min: currentDate
            },
            visibility: {
                disabled: true,
                theme: 'light'
            }
        },
        actions: {
          clickArrow: assignEventsToCalendar
        }
    };

    var calendar = new VanillaCalendar("#calendar", options);
    calendar.init();

    assignEventsToCalendar();

});

const assignEventsToCalendar = function() {
  let eventData = data;
  for (const {month, days} of eventData) {
    for (const {day, events} of days) {
      const key = day.split('-').map(p => p.padStart(2, '0')).join('-');
      let dayElement = document.querySelector(`[data-calendar-day="${key}"]`);
 
      if (dayElement) { // only apply flair if day exists (is in current month)
        let eventWrapper = document.createElement("div");
        eventWrapper.classList.add("event-wrapper");
        dayElement.append(eventWrapper);

        for (const {title, category} of events) {
          let singleEvent = document.createElement("div");
          singleEvent.classList.add("event", category);
          eventWrapper.append(singleEvent);
        }
      }
    }
  }
};

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

Sending a function along with event and additional arguments to a child component as a prop

I've managed to set up a navigation bar, but now I need to add more complexity to it. Specifically, I have certain links that should only be accessible to users with specific permissions. If a user without the necessary permissions tries to access the ...

PHP WebService, exclusively containing private variables within an empty array

I'm attempting to create a PHP webservice. In the "Aluno" class, there are 2 private variables. After struggling all day with this, I finally discovered that if I change those variables to public, everything works as expected. However, if they remain ...

Diverse jQuery Quiz Challenge

I need to create a quiz with 10 questions, each having 4 answers with one correct option. The question structure is as follows: 3 easy questions one differential question with two answers leading to different paths based on the user's choice 5 follo ...

Issue with printing data consecutively using Javascript

My JavaScript code aims to display the content of the body tag again when the add button is clicked. The purpose is to add authors, with each author being added in sequence. For example, if there is only 1 author present, the user simply selects whether th ...

The function passed to the modal is not functioning correctly when stored within the state

Is it possible to create a unique modal that can be utilized for multiple actions on the same page? To achieve this, I have implemented a state to store the title, description, and submit function for modal click and modal open state. In addition, I want t ...

Incomplete JSON response being received

We set up an express server to call an API and successfully requested the JSON object in our server. However, we are facing an issue where the JSON data is getting cut off when being displayed as a complete object on the client side. We tried using parse i ...

Troubleshooting problem with input and textarea losing focus in Ajax requests

Experiencing an issue with submitting information using ajax. For instance, there are 20 rows. When a row is clicked, it displays all details about services. $('tr').click(function() { var servicesUpdateId = $(this).attr('data&a ...

Associate information with HTML elements

I've come across this question multiple times, but the solutions are mostly focused on HTML5. My DOCTYPE declaration is: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> I'm looking t ...

Transforming data from a singular object into an array containing multiple objects with key-value pairs

Looking for assistance with converting data from a single object in JSON format to another format. Here is the initial data: var originalData = { "1": "alpha", "2": "beta", "3": "ceta" } The desired format is as follows: var convertedData = ...

Guide to executing a server-side FUNCTION within a specific namespace room exclusively with the help of socket.io, express, and node.js

I've been developing an online multiplayer game using socket.io, express, and node.js. The server is supposed to detect the number of users connected to a specific room within a namespace and start the game if there are more than two players. However, ...

Accessing the selected list item from an unordered list in Vue.js

How can I capture the selected item from a dropdown-style list and perform operations based on that selection? In my list, each item is associated with a key for unique identification, except for 'Create New Filter'. I am seeking guidance on ho ...

Is it possible for JavaScript to be cached when it is located within the body tag of an HTML document?

Currently, I am exploring the topic of How to optimize HTML rendering speed, and came across the idea that scripts in the HEAD tag can be cached. I'm curious, is it possible to cache JavaScript in the BODY tag? If not, I wonder why YUI suggests placi ...

Troubleshooting AngularJS Get Function Failure

New to the world of AngularJS, I find myself faced with a challenge. My .NET MVC WebAPI Restful app is up and running on an IIS server. However, when I attempt to query the API using , the response I receive is: [{"Id":1,"Name":"Glenn Block","Created":"00 ...

Angular: What methods can I utilize to prevent my $http requests from causing UI blockage?

The following code snippet is from my controller: PartnersService.GetNonPartnerBanks().success(function (data) { vm.nonPartnerBanksList = data; }).error( function () { vm.nonPartnerBanksList = []; }); This code calls the service s ...

Using Javascript libraries on a Chromebook: A comprehensive guide to getting started

Doing some coding on my chromebook and wondering if it's possible to download and utilize libraries such as jQuery. Would really appreciate any assistance with this! ...

Error encountered with the Angular 2 routing system

Currently, I am facing an issue with my Angular 2 router module. Whenever I try to access the link /city, I encounter an error message saying 'ERROR Error: Uncaught (in promise): Error: Cannot activate an already activated outlet Error: Cannot activat ...

Removing a Request with specified parameters in MongoDB using NodeJS

Working with Angular 4 and MongoDB, I encountered an issue while attempting to send a delete request. My goal was to delete multiple items based on their IDs using the following setup: deleteData(id) { return this.http.delete(this.api, id) } In order ...

Retrieve specific information using the identifier from the URL parameters during server-side rendering

I am trying to fetch data with a parameter from the URL using Nextjs. However, I am facing an issue where the parameter value is undefined. Here is the code snippet: const Room = () => { let fetchData; let roomId; const getID = () => { con ...

Using the Ajax method from a separate class in TypeScript: A step-by-step guide

Recently, I started learning about typescript and ajax. One of the challenges I encountered was while creating a method in typescript for making ajax calls that can be used across classes: myFunc(value: string): JQueryPromise<any> { var dfd = $. ...

What is the best way to align HTML inputs within a grid, whether it be done automatically or manually using JavaScript?

Arrange 20 HTML inputs with various data types into grid-columns as the user inputs data. Ensure that the grid container has div elements correctly positioned for output. ...