fullcalendar.io 5: addEventSource not work from external function - javascript

For a small project I want to add events at runtime.
The actual calendar is created with data from a database. The separate script creates additional events, which are created dynamically at runtime of the calendar. These events should be added to the existing calendar afterwards.
For testing I have a calendar and an external button. If you click on the button, an event should be added to the calendar. Calendar is created and the click is recognized. But no event is added.
Where is the thought error?
The HTML
<button class="holiday">Add Feiertage</button>
<div id='calendar'></div>
The Code:
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek'
},
initialDate: '2020-11-12',
businessHours: true, // display business hours
editable: true,
events: [
{
title: 'Business Lunch',
start: '2020-11-03T13:00:00',
constraint: 'businessHours'
},
{
title: 'Meeting',
start: '2020-11-13T11:00:00',
constraint: 'availableForMeeting', // defined below
color: '#257e4a'
},
{
title: 'Conference',
start: '2020-11-18',
end: '2020-11-20'
},
{
title: 'Party',
start: '2020-11-29T20:00:00'
},
// areas where "Meeting" must be dropped
{
groupId: 'availableForMeeting',
start: '2020-11-11T10:00:00',
end: '2020-11-11T16:00:00',
display: 'background'
},
{
groupId: 'availableForMeeting',
start: '2020-11-13T10:00:00',
end: '2020-11-13T16:00:00',
display: 'background'
},
// red areas where no events can be dropped
{
start: '2020-11-18',
title: 'Test-Holiday',
overlap: false,
display: 'background',
color: '#ff9f89'
}
]
});
calendar.render();
});
// external events by Click
jQuery(document).ready(function($) {
$('.holiday').on('click', function() {
console.log('klick');
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl);
//var src = calendar.getEventSources(); // give me a empty array
calendar.addEventSource(
{
events: [ // put the array in the `events` property
{
title : 'Test-Event',
start : '2020-11-11',
overlap: false,
display: 'background',
color: '#ff9f89'
}
]
});
calendar.refetchEvents();
});
});
});
Here is my Test:
https://jsfiddle.net/LukasHH/tu14xfwr/

The calendar variable you're using for calendar.addEventSource refers to a different FullCalendar instance than the one which is shown on your page. You have created a completely new calendar - but then didn't render it to the page. That's why you don't get errors, but also nothing useful happens.
The original calendar is defined and populated inside your document.addEventListener('DOMContentLoaded', function() { block, but you tried to create a new one inside your jQuery(document).ready(function($) { block. You need to use the existing reference to calendar - but of course it's out of scope when you need it, because you're in a different code block.
Now, document.addEventListener('DOMContentLoaded', function() { and jQuery(document).ready(function($) { are essentially equivalent, it's just that one is written in native JS and one is jQuery syntax. They basically do the same task - i.e. delay execution of the code until the DOM is completely loaded. Therefore it doesn't make much sense or add any value to have both of them in the page at the same time. Just use one block to include all of your code, and then you won't have any scope problems regardless.
As well as that, for similar reasons it also makes no sense to have another document.addEventListener('DOMContentLoaded', function() { within the jQuery "ready" block! You simply don't need it. I can only assume you didn't understand what that code did and thought it was part of fullCalendar - it's not.
And
var i = calendar.initialEvents();
console.log(i);
makes no sense. There's no method called initialEvents in fullCalendar and you don't seem to be trying to use i for anything anyway, so you can just remove these lines.
e.g.
jQuery(document).ready(function($) {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
//...etc
});
calendar.render();
$('.holiday').on('click', function() {
calendar.addEventSource({
events: [ // put the array in the `events` property
{
title: 'Test-Event',
start: '2020-11-11',
overlap: false,
display: 'background',
color: '#ff9f89'
}
]
});
});
Demo: https://jsfiddle.net/32w4kLvg/

Related

GetEvents from FullCalendar

I'm working with Full Calendar I want to create a button that take all the events from the calendar and send them to my database. But when trying to call the getEvents method referenced here from the calendar object, I cannot get it to work. The method doesn't seem to exist. I get undefined method.
Below is a snippet of the initialization of the calendar.
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay'
},
initialDate: '2020-09-12',
navLinks: true, // can click day/week names to navigate views
selectable: true,
selectMirror: true,
select: function(arg) {
var title = prompt('Event Title:');
if (title) {
calendar.addEvent({
title: title,
start: arg.start,
end: arg.end,
allDay: arg.allDay
})
}
calendar.unselect()
},
eventClick: function(arg) {
if (confirm('Are you sure you want to delete this event?')) {
arg.event.remove()
}
},
editable: true,
dayMaxEvents: true, // allow "more" link when too many events
events: [
{
title: 'All Day Event',
start: '2020-09-01'
},
{
title: 'Long Event',
start: '2020-09-07',
end: '2020-09-10'
},
{
groupId: 999,
title: 'Repeating Event',
start: '2020-09-09T16:00:00'
},
{
groupId: 999,
title: 'Repeating Event',
start: '2020-09-16T16:00:00'
},
{
title: 'Conference',
start: '2020-09-11',
end: '2020-09-13'
},
{
title: 'Click for Google',
url: 'http://google.com/',
start: '2020-09-28'
}
]
});
calendar.render();
I use the last version of Full Calendar (v5)
When I try to create a button that will get the calendar then retrieve all the events and send it to my database I get error saying that the function doesn't exist.
Here is how I do that :
var calendar = document.getElementById("calendar");
/* I can do that since I have my calendar with the id "calendar"
And then I try use the getEvents function
*/
var events = calendar.getEvents();
/* Show undefined */
<div id="calendar"></div>
Super Important Note: I realized that the function doesn't exist since I try to apply it to the HTML element and not the FullCalendar JS object. So my question is how can I get a FullCalendar JS Object from the HTML element in order to retrieve the events that the user has saved ??
Your problem is because var calendar = document.getElementById("calendar"); fetches the HTML element into which the rest of the calendar's HTML was added by fullCalendar. It does not fetch the fullCalendar instance which was generated by new FullCalendar.Calendar when you intialised the calendar. It's the latter which exposes the functions to manipulate the calendar or get data from it.
Notice how you already use that object in your code to call fullCalendar's render function, e.g. calendar.render();.
(The HTML element object just contains standard functions found on any HTML element, not anything specific to fullCalendar.)
So in summary you need to use the calendar variable you created from the new FullCalendar... instantiation. If you need access to that outside the scope it was originally declared in (which is the callback of the DOMContentLoaded event handler), then one way round that is to make it a global variable, e.g.
var calendar; //global variable
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
calendar = new FullCalendar.Calendar(calendarEl, {
....
});
calendar.render();
});
Then somewhere else in your code, wherever you need it, you can write
var events = calendar.getEvents();

how to ban user from adding event in fullcalendar.io(version 5.0.1)?

I am working on a project using bootstrap 4 and fullcalendar.io (version5.0.1).
I use "select" function to let user click on specific date to add event.
but I want to limit user to add one event only in fullcalendar.
I tried to get length of added event but fail.
code is here.
enter code here
document.addEventListener('DOMContentLoaded', function() {
var calendar = new FullCalendar.Calendar(calendarEl, {
select: function(arg) {
input_Form.classList.remove("collapse");
dateA.value=new Intl.DateTimeFormat('en-US').format(arg.start);
submitA.onclick=function(){
input_Form.classList.add("collapse");
if (textareaContent.value) {
calendar.addEvent({
title:textareaContent.value,
start: arg.start,
end: arg.end,
allDay: arg.allDay,
})
textareaContent.value="";
}
calendar.unselect()
};
},
eventClick: function(arg) {
input_Form.classList.remove("collapse");
textareaContent.value=arg.event.title;
submitA.onclick=function(){
input_Form.classList.add("collapse");
arg.event.remove()
if (textareaContent.value) {
calendar.addEvent({
title:textareaContent.value,
start: arg.event.start,
end: arg.event.end,
allDay: arg.event.allDay
})
textareaContent.value="";
}
calendar.unselect()
};
},

Fullcalendar refetch eventsource

As the title says, I have a question regarding EventSource in the fullcalendar.
At the moment I can load 1 google calendar in the fullcalendar. And know how to add multiple google calendars.
However, I want to use checkboxes (linked to their own google calendar), I dynamically create an array with the googleCalendarIds, all this works, but I can't get the calendar to "refetch" all the event from the google calendars in the array.
At the moment, this is the code I use to populate the calendar:
document.addEventListener('DOMContentLoaded', function() {
var selected = [];
$('.badgebox:checked').each(function() {
selected.push({
'googleCalendarId' : $(this).val(),
'className' : $(this).data('color')
});
});
$('.badgebox').on('click', function() {
if($(this).prop('checked')) {
selected.push({
'googleCalendarId' : $(this).val(),
'className' : $(this).data('color')
});
$('#calendar').fullCalendar('refetchResources');
}else{
index = selected.findIndex(obj => obj.googleCalendarId === $(this).val());
selected.splice(index, 1);
$('#calendar').fullCalendar('refetchResources');
}
});
var calendarEl = document.getElementById('calendar');
calendar = new FullCalendar.Calendar(calendarEl, {
header: {
center: 'dayGridMonth,timeGridWeek'
},
views: {
dayGridMonth: {
titleFormat: { year: 'numeric', month: '2-digit', day: '2-digit' }
}
},
plugins: [ 'dayGrid', 'timeGrid', 'bootstrap', 'googleCalendar' ],
googleCalendarApiKey: 'api key',
eventSources: selected,
eventClick: function(info) {
info.jsEvent.preventDefault();
},
defaultView: 'timeGridWeek',
weekNumbers: true,
locale: 'nl',
themeSystem: 'bootstrap',
nowIndicator: true
});
calendar.render();
});
But what I am getting is an error:
TypeError: $(...).fullCalendar is not a function
I have loaded all the files needed (and can see they are loaded).
Edit current code
This is the code I use now, but still not sure how to fix the resources part (refreshing):
document.addEventListener('DOMContentLoaded', function() {
var curSource = [];
$('.badgebox:checked').each(function() {
curSource.push({
'googleCalendarId' : $(this).val(),
'className' : $(this).data('color')
});
});
var newSource = [];
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
schedulerLicenseKey: 'key',
header: {
center: 'dayGridMonth,timeGridWeek'
},
views: {
dayGridMonth: {
titleFormat: { year: 'numeric', month: '2-digit', day: '2-digit' }
}
},
plugins: [ 'dayGrid', 'timeGrid', 'bootstrap', 'googleCalendar', 'resourceTimeGrid', 'resourceDayGrid' ],
googleCalendarApiKey: 'apikey',
eventSources: curSource,
eventClick: function(info) {
info.jsEvent.preventDefault();
},
defaultView: 'timeGridWeek',
weekNumbers: true,
locale: 'nl',
themeSystem: 'bootstrap',
nowIndicator: true
});
$('.badgebox').on('change', function() {
if($(this).prop('checked')) {
newSource.push({
'googleCalendarId' : $(this).val(),
'className' : $(this).data('color')
});
}else{
index = newSource.findIndex(obj => obj.googleCalendarId === $(this).val());
newSource.splice(index, 1);
}
curSource = newSource;
calendar.getEventSources().forEach(eventSource => {
eventSource.remove()
});
calendar.addEventSource(curSource);
});
calendar.render();
});
Any idea?
Your logic for adding and removing event sources is flawed - it'll remove all the previous sources, but only ever add the currently selected one (well, except that you never clear newSource so it'll contain all sorts of duplication after a while). The other problem is that when you write calendar.addEventSource(curSource); you're adding an array of event sources (even though it only ever contains one item) but adding it as if it was a single event source object. Therefore it's not in the format fullCalendar expects, so it doesn't add anything.
Instead you can just use the same logic you use when you first declare the calendar, to loop through all the currently selected checkboxes and set all of them as the current sources. This is the simplest way to do it. Just move that logic into a function so you can re-use it. It also removes the necessity for global objects containing the list of sources. Something like this:
function getEventSources() {
var sources = [];
$(".badgebox:checked").each(function() {
sources.push({
id: $(this).val(),
'googleCalendarId' : $(this).val(),
className: $(this).data("color")
});
});
return sources;
}
Then in the calendar config, set the initial event sources by calling the function:
eventSources: getEventSources(),
And handle the "change" event on the checkboxes like this:
$(".badgebox").on("change", function() {
//remove event sources
calendar.getEventSources().forEach(eventSource => {
eventSource.remove();
});
//get currently selected sources
var sources = getEventSources();
//add each new source to the calendar
sources.forEach(eventSource => {
calendar.addEventSource(eventSource);
});
});
I made a live demo here: https://codepen.io/ADyson82/pen/Jjoovym. I couldn't use google calendars for the demo obviously so I've done it with hard-coded lists of events, but the overall logic of the process is identical.

why does my events load after i click the next button full calendar?

Im using 2 fullcalendar. I'm so confused why my events in my 2nd calendar is not loading. This is the code of my 2nd calendar.
` $("#calendar-modal").html("");
var scheduleClick=info.event.start.toISOString();
var calendarEl = document.getElementById('calendar-modal');
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: [ 'timeGrid' ],
header: {
left: false,
center: 'title',
right: false
},
defaultView:'timeGrid',
defaultDate:scheduleClick,
displayEventTime:false,
allDaySlot: false,
slotEventOverlap:false,
minTime:"07:00",
maxTime:"24:00",
eventSources:[
{
url:'something.php',
method:'POST',
color: '#87a900',
textColor: 'black'
}
],
});
calendar.refetchEvents(); // I've tried using refetch events
calendar.render();`
I hope someone can clarify my mistake in this code. I've searched about this topic and i have seen something related to next and prev buttons. Does the calendar only render events after clicking next and prev?

angularjs ui calendar not displaying added event

I am trying to add a new events to the ui calendar using ui bootstrap modal box. However, its not showing on the calendar. Below I have created the function for the day click event which contains the code for the modal box:
$scope.dayClickEvent = function(date,jsEvent,view){
//open model view for adding a event title
var creatEventModalInstance = $modal.open({
templateUrl: '/js/schedule/event_modal.html',
controller: function($scope, $modalInstance){
$scope.add = function(event){
$modalInstance.close(event);
};
$scope.close = function(){
$modalInstance.dismiss('cancel');
};
}
});
Here is the code for the ui configuration for the calendar:
$scope.uiConfig = {
calendar:{
height: 450,
editable: true,
header:{
left: 'month basicWeek basicDay agendaWeek agendaDay',
center: 'title',
right: 'today prev,next'
},
dayClick: $scope.dayClickEvent
}
};
Also the code for the event source to provide ui calendar with data about the events:
$scope.eventSources = {
events: [
{
title: 'Event1',
start: '2015-01-18'
},
{
title: 'dsadas',
start: '2015-01-18'
}
// etc...
],
color: 'yellow', // an option!
textColor: 'black' // an option!
};
So, what I am doing wrong and thanks in advance.
$scope.eventSources is an array that includes one or more event source objects.
It's an extended form meant to allow you to add multiple event sources.
an Event Source Object includes the events array as well as any Event Source Options related to the events - such as text or background colours.
Therefore you must to add an object for each event source
- then you include your events array within the object - along with any options.
...in your example you put the events array directly within an $scope.eventSources object...
To correct:
- make $scope.eventSources an array ie use [square brackets]
- put the events:[] array inside an object ie within {curly brackets}
try something like this:
$scope.eventSources = [
//this is event source object #1
{
events: [ // put the array in the `events` property
{
title: 'Event1',
start: '2015-01-24'
},
{
title: 'Event2',
start: '2015-01-28'
}
],
color: 'black', // an Event Source Option!
textColor: 'yellow' // an Event Source Option!
}
];
as outlined in this answer, you can add multiple sources by referencing objects, like:
$scope.eventSources = [$scope.eventSourceObject1, $scope.eventSourceObject2, etc...],
(you can call your Event Source Objects whatever you want, as long as they're correctly constructed)
Again each event source will have to be an object that includes the events array inside.

Categories