0

I'm having problems with adding events in 'FullCalendar', please keep in my mind that my javascript knowledge is pretty small, so the solution may be simple.

Either way, I've started using FullCalendar to display events from my already existing database, so far it's working fine, except that I struggle to add an event after rendering the calendar.

I've followed the documentation, my code:

document.addEventListener('DOMContentLoaded', function() {
      var calendarEl = document.getElementById('calendar');
      var calendar = new FullCalendar.Calendar(calendarEl, {
         // Calendar options
      });
      calendar.render();
});

function addevent() {
      calendar.addEvent({
         start: '2022-05-23T14:00:00',
         end: '2022-05-23T15:00:00',
         title: 'Test'
      }
}

The function addevent() is called after completing a form on the page, the form is submitted with Ajax and stored in the database, a page refresh would be needed to display that event, but I would like to show it right away.

However, im getting the error 'calender is not defined', which makes sense because I didn't clarify the variable. I have no clue how to get this working, and I also can't seem to find it in the documentation. After some googling I've tried the following code:

function addevent() {
    var event = {
          start: '2022-05-23T14:00:00',
          end: '2022-05-23T15:00:00',
          title: 'Test'
    }

    $('#calendar').fullCalendar('renderEvent',event,true);
}

Which returns '$(...).fullCalendar is not a function', this seems to be working on older versions I think, I am using version 5.

Any help is appreciated, thanks in advance!

Mark
  • 31
  • 1
  • 6

1 Answers1

0

This is simply about variable scope. calendar isn't available in your addevent function because you declared it inside the DOMContentLoaded callback, and therefore it's only accessible within that callback function.

One way to solve this is to make the variable global:

var calendar = null;

document.addEventListener('DOMContentLoaded', function() {
      var calendarEl = document.getElementById('calendar');
      calendar = new FullCalendar.Calendar(calendarEl, {
         // Calendar options
      });
      calendar.render();
});

function addevent() {
      calendar.addEvent({
         start: '2022-05-23T14:00:00',
         end: '2022-05-23T15:00:00',
         title: 'Test'
      }
}

Reference / wider reading: What is the scope of variables in JavaScript?


P.S. You're correct that $('#calendar').fullCalendar('renderEvent',event,true); is the syntax from older versions of fullCalendar, specifically v3 and earlier when fullCalendar was implemented as a jQuery plugin.

ADyson
  • 57,178
  • 14
  • 51
  • 63