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

Utilize Android to Extract Data from JSON

I am attempting to retrieve and parse the list of 4chan boards using their json api. The JSON data I am trying to parse can be found here: . Upon verification, the json appears to be valid. However, I am encountering the following error message: 11-21 17 ...

Employing a pair of interdependent v-select components to prevent any duplicate entries

I am currently working with two v-select boxes that share similar data. In my scenario, I extract attachments from an email and load them into an array. The issue I encountered is that the first select box should only allow the selection of one document, w ...

How to upload numerous chosen files from an Android device using PHP script

When attempting to upload multiple files using the file selection option on an Android mobile device, I encountered an issue of not being able to select specific multiple files. I tried utilizing the multiple-form/data and multiple="multiple" attributes w ...

Discover the total value of the elements in a json array within mysql while applying filtering

I'm currently using mariadb version 10.2.43-MariaDB-1:10.2.43+maria~bionic Here is the schema of the table: The table consists of a column called id and an array named details, which contains the following two sets of data: { "id": 9, ...

What is the best way to integrate a Sequalize API into my React project?

I am looking for guidance on how to retrieve records from my MYSQL database and integrate it into my API. I am unsure about the routing process (do I need to create a component?) and struggling to find resources on using sequelize with React. Any assista ...

Remove specific data from jQuery datatables using data attribute

My jQuery datatable is loaded with data from a database without any filtering by default, providing all the necessary information for users. In addition to the built-in search functionality of jQuery datatables, I have incorporated custom search input fiel ...

Is it accurate to consider all JavaScript code and variables as inherent properties of an execution context?

It's worth considering that everything in JS code can be viewed as a property of an execution context, whether it's a global, function, or eval() execution context. Why is this the case? Each execution context has its own unique lexical and v ...

Enhance your Sails.js model by incorporating a custom instance method as a new property

As a JavaScript programmer still learning the ropes, I encountered a challenge while working with Sails.js and creating a model. Here is what I have so far: module.exports = { tableName: 'FOO_TABLE', attributes: { FOO: 'st ...

Javascript does not function on sections generated by ajax

I'm facing an issue with a JavaScript function not working on a dynamically generated part using AJAX. Here is the AJAX call: <script> $(window).on('scroll', function() { $("#preloadmore").show(); if ($(window).height() + $(window ...

Caution: flattenKids(): Two children with identical keys, `false`, have been detected in the ReactJS environment

Currently, I am working on creating a clickable list where each item redirects me to another page upon clicking. Below is the render method: render() { const quesItems = this.state.questions.map((question, i) => { return ( <li key={this.prop ...

Uh oh! The dreaded Error [ERR_HTTP_HEADERS_SENT] has struck again in the Node Express MongoDB world. Headers cannot be set after they have

Hey there, newbie in the coding world! I've been diving into a guide on setting up a backend server using Node.js, Express, and MongoDB. You can find the guide here: But I seem to keep running into an error when testing with Postman. Error [ERR_HTTP ...

What is the method to combine multiple style values in vue.js?

Is there a way to create a div with a box shadow where the values can be changed using a slider? I am having trouble using more than one value stored in a data variable. Any suggestions on how to achieve this? <div :style="{ borderRadius: x_axis y_ ...

When programming with PHP and JavaScript, managing events' start dates and end dates

In my current project, I am developing a script that deals with events. An event is scheduled to start on 12/02/2016 at 11:20 and end on 01/04/2016 at 8:20. When the end date is reached, I need to trigger a specific action using JavaScript. if (t.getFullY ...

Customize the appearance of disabled dates in the eonasdan-datetimepicker styling

I am seeking to customize the default styles for the "eonasdan-datetimepicker" (https://github.com/Eonasdan/bootstrap-datetimepicker) by implementing a basic hover message feature. The CSS attributes currently applied to disabled dates are as follows: .bo ...

Using the PUT method in combination with express and sequelize

I am having trouble using the PUT method to update data based on req.params.id. My approach involves retrieving data by id, displaying it in a table format, allowing users to make changes, and then updating the database with the new values. Here is the co ...

Enhancing List Page Functionality with AngularJS/MVC5 Search Feature

As I work on enhancing the List page, my main focus is on implementing a search feature. While the code below effectively displays data in a list format, I am uncertain about how to start incorporating a search functionality into this page. HTML: <bo ...

Issue with burger menu functionality, button unresponsive

Two files are involved in this issue, one is a Vue file and the other is a JavaScript file. The JavaScript file contains an array and the problem is being described in the console. Additionally, there may be an issue with items as sometimes the same error ...

Can you explain the significance of 1x, 3x, etc in the Karma code coverage report for Angular unit testing?

I am a beginner when it comes to Unit Testing in Angular. Recently, I set up karma with code coverage using angular-cli. After running the command ng-test, I checked out the code coverage report and noticed references like 1x, 3x, etc. next to my code line ...

What is the best way to attach an onClick event to a PHP-generated link?

Currently, I'm attempting to implement an onclick event on a link within a PHP file. $body2 .= '<td class="sampling-list-td download-link">' . '<a ' . 'class="sampling-list-download" ' . 'href="#" ' . ...

Syntax error triggered and caught by ajaxError

I have implemented a client-side ajax error handler using the following code: $(document).ajaxError(processAjaxError); $.getJSON('/data.json'); In the server side, I have defined a function as shown below: def get(self): self.response.he ...