Search code examples
javascriptfullcalendarfullcalendar-4

How can i get the fullcalendar v.4.2.0 instance?


So I have a fullCalendar (v.4.2.0) instance in my page (loaded/built on document.ready) and I want to access that fullCalendar instance in other functions to add events dynamically.

Using $('#calendar').fullCalendar('getView') it shows an error that the fullCalendar() method does not exist:

$(...).fullCalendar is not a function

How can I access that instance?

The code that I'm using to generate the calendar is the following:

var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
    plugins: [ 'timeGrid', 'dayGrid' ],
        defaultView: 'timeGridWeek', 
        height: 700,
        locale: 'pt',
        allDaySlot: false,
        handleWindowResize: true,
        events: [
            {
                title: 'Teste1', // a property!
                start: '2019-07-23 16:00', 
                end: '2019-07-23 17:00', 
                backgroundColor: '#fcba03',
                borderColor: '#fcba03',
            }
        ]
    });
calendar.render();

Solution

  • Since you are using fullCalendar version 4, it is no longer written as a jQuery plugin, and so jQuery syntax to access the methods cannot be used. Instead, simply refer to your calendar variable (which probably needs to have a wide scope in your application - either global or easily accessible some other way). You'll notice that your existing code already does exactly that when it calls calendar.render();.

    Additionally, in the specific case of the "getView" method, this has been replaced simply with a view property which refers to the current view.

    For example (see the last line):

    var calendarEl = document.getElementById('calendar');
    var calendar = new FullCalendar.Calendar(calendarEl, {
        plugins: [ 'timeGrid', 'dayGrid' ],
            defaultView: 'timeGridWeek', 
            height: 700,
            locale: 'pt',
            allDaySlot: false,
            handleWindowResize: true,
            events: [
                {
                    title: 'Teste1', // a property!
                    start: '2019-07-23 16:00', 
                    end: '2019-07-23 17:00', 
                    backgroundColor: '#fcba03',
                    borderColor: '#fcba03',
                }
            ]
        });
    
    calendar.render();
    
    var vw = calendar.view; //get the current view
    

    Reference documentation

    Documentation of the view property

    Version 3 to Version 4 upgrade guide