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/
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()
};
},
I am using meteor and fullcalendar. I am trying to use the dayClick:function in my template but it is not working.
I would like the dayClick to fire when I click on the day without the use of jQuery. I understand that the way the Template.....events is setup that it will not work. I clearly do not understand some(many)thing(s).
Template:
JS
Template.calendar2.helpers({
calendarOptions: {
// Standard fullcalendar options
height: 700,
hiddenDays: [],
slotDuration: '01:00:00',
minTime: '08:00:00',
maxTime: '19:00:00',
lang: 'en',
// Function providing events reactive computation for fullcalendar plugin
events: function(start, end, timezone, callback) {
//console.log(date);
//console.log(start);
//console.log(end);
//console.log(timezone);
var events = [];
// Get only events from one document of the Calendars collection
// events is a field of the Calendars collection document
var calendar = CalEvents.findOne(
{ "_id":"myCalendarId" },
{ "fields": { 'events': 1 } }
);
// events need to be an array of subDocuments:
// each event field named as fullcalendar Event Object property is automatically used by fullcalendar
if (calendar && calendar.events) {
calendar.events.forEach(function (event) {
eventDetails = {};
for(key in event)
eventDetails[key] = event[key];
events.push(eventDetails);
});
}
callback(events);
},
// Optional: id of the calendar
id: "calendar1",
// Optional: Additional classes to apply to the calendar
addedClasses: "col-md-8",
// Optional: Additional functions to apply after each reactive events computation
autoruns: [
function () {
console.log("user defined autorun function executed!");
}
]
},
});
Here is the event
Template.calendar2.events({
dayClick:function( date, allDay, jsEvent, view ) {
CalEvents.insert({title:'New Event',start:date,end:date});
Session.set('lastMod',new Date());
}
)};
I guess I didnt have a clear enough understanding of how full calendar works. I did not need to a click event to initiate an date/event. fullcalendar already has a way to do that with dayClick: function(); I just needed to place within calendaroptions{};
dayClick: function(date, jsEvent, view) {
CalEvents2.insert({title:'NEW', start:date._d, end:date._d});
Session.set('clickedDate', tempEvent);
IonModal.open('_cal2Modal');
},
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.
I'm trying to load data into an FullCalendar, using Json. But i can't load the data:
The controller:
ppublic ActionResult GetEvents()
{
List<Models.Events> events = new List<Models.Events>()
{
new Models.Events("Fremvising","2013-01-11T14:08:00Z", "2013-01-11T16:09:00Z", false),
new Models.Events("Fremvising","2013-01-12T15:09:00Z", "2013-01-11T17:10:00Z", false),
new Models.Events("Fremvising","2013-01-13T16:10:00Z", "2013-01-11T18:11:00Z", false),
new Models.Events("Fremvising","2013-01-14T17:11:00Z", "2013-01-11T19:12:00Z", false),
new Models.Events("Fremvising","2013-01-15T18:12:00Z", "2013-01-11T20:13:00Z", false),
new Models.Events("Fremvising","2013-01-16T19:13:00Z", "2013-01-11T21:14:00Z", false)
};
return Json(events, JsonRequestBehavior.AllowGet);
}
And the javascript:
$(document).ready(function () {
/* initialize the external events
-----------------------------------------------------------------*/
$('#external-events div.external-event').each(function () {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject = {
title: $.trim($(this).text()) // use the element's text as the event title
};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject);
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
/* initialize the calendar
-----------------------------------------------------------------*/
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'agendaWeek,agendaDay',
height: 650,
// url:,
}, events: [
$.getJSON("#Url.Action("GetEvents")", function (locationsArray) {
$.each(locationsArray, function (index, location) {
title : location.title;
start: location.start;
end: location.end;
allDay: location.editable; // will make the time show
});
})
],
allDaySlot: false,
//minTime: 10,
//maxTime: 21,
dayNames: ['Søndag', 'Mandag', 'Tirsdag', 'Onsdag',
'Torsdag', 'Fredag', 'Lørdag'],
dayNamesShort: ['Søn', 'Man', 'Tirs', 'Ons', 'Tors', 'Fre', 'Lør'],
editable: true,
defaultView: 'agendaWeek',
droppable: true, // this allows things to be dropped onto the calendar !!!
drop: function (date, allDay) { // this function is called when something is dropped
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
copiedEventObject.allDay = allDay;
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// is the "remove after drop" checkbox checked?
if ($('#drop-remove').is(':checked')) {
// if so, remove the element from the "Draggable Events" list
$(this).remove();
}
}
});
});
$('#tabs').tabs({
show: function (event, ui) {
$('#calendar').fullCalendar('render');
}
});
For some reason it doesnt get the json result.
The Json request
0: {title:Fremvising, start:2013-01-11T14:08:00Z, end:2013-01-11T16:09:00Z, editable:false}
1: {title:Fremvising, start:2013-01-12T15:09:00Z, end:2013-01-11T17:10:00Z, editable:false}
2: {title:Fremvising, start:2013-01-13T16:10:00Z, end:2013-01-11T18:11:00Z, editable:false}
3: {title:Fremvising, start:2013-01-14T17:11:00Z, end:2013-01-11T19:12:00Z, editable:false}
4: {title:Fremvising, start:2013-01-15T18:12:00Z, end:2013-01-11T20:13:00Z, editable:false}
5: {title:Fremvising, start:2013-01-16T19:13:00Z, end:2013-01-11T21:14:00Z, editable:false}
You have incorrectly defined the events property of your FullCalendar. You have assigned it to a javascript array but that's incorrect because your data is coming from the server. You should set it to an anonymous function. Also you seem to be triggering an AJAX request to the server but inside the success callback you are doing absolutely nothing with the results other than looping through them but you never pass them to the FullCalendar. Here's the correct way to define the events property:
events: function (start, end, callback) {
$.getJSON("#Url.Action("GetEvents")", function (locationsArray) {
var result = $(locationsArray).map(function () {
return {
title: this.title,
start: this.start,
end: this.end,
allDay: this.editable
};
}).toArray();
callback(result);
});
},
Notice how we are performing a transformation over the result coming from the server (which wouldn't have been necessary of course if you had used view models) and then we are calling the callback property with this transformed resultset.
Alright and here's a step by step guide:
Create a new ASP.NET MVC 4 application using the Internet Application Template
Modify HomeController to look like this:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult GetEvents()
{
var events = new[]
{
new { title = "Fremvising", start = "2013-01-11T14:08:00Z", end = "2013-01-11T16:09:00Z", editable = false },
new { title = "Fremvising", start = "2013-01-12T15:09:00Z", end = "2013-01-11T17:10:00Z", editable = false },
new { title = "Fremvising", start = "2013-01-13T16:10:00Z", end = "2013-01-11T18:11:00Z", editable = false },
new { title = "Fremvising", start = "2013-01-14T17:11:00Z", end = "2013-01-11T19:12:00Z", editable = false },
new { title = "Fremvising", start = "2013-01-15T18:12:00Z", end = "2013-01-11T20:13:00Z", editable = false },
new { title = "Fremvising", start = "2013-01-16T19:13:00Z", end = "2013-01-11T21:14:00Z", editable = false }
};
return Json(events, JsonRequestBehavior.AllowGet);
}
}
Download FullCalendar and put it into the Scripts folder
Modify ~/Views/Shared/_Layout.cshtml to look like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title - My ASP.NET MVC Application</title>
#RenderSection("styles", required: false)
</head>
<body>
#RenderBody()
#Scripts.Render("~/bundles/jquery")
#RenderSection("scripts", required: false)
</body>
</html>
And ~/Views/Home/Index.cshtml like that:
<div id="calendar"></div>
#section styles {
<link href="~/scripts/fullcalendar-1.5.4/fullcalendar/fullcalendar.css" rel="stylesheet" />
}
#section scripts {
<script type="text/javascript" src="~/scripts/fullcalendar-1.5.4/fullcalendar/fullcalendar.js"></script>
<script type="text/javascript">
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'agendaWeek,agendaDay',
height: 650,
},
events: function (start, end, callback) {
$.getJSON("#Url.Action("GetEvents")", function (locationsArray) {
var result = $(locationsArray).map(function () {
return {
title: this.title,
start: this.start,
end: this.end,
allDay: this.editable
};
}).toArray();
callback(result);
});
},
allDaySlot: false,
dayNames: ['Søndag', 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag'],
dayNamesShort: ['Søn', 'Man', 'Tirs', 'Ons', 'Tors', 'Fre', 'Lør'],
editable: true,
defaultView: 'agendaWeek',
droppable: true,
drop: function (date, allDay) { // this function is called when something is dropped
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
copiedEventObject.allDay = allDay;
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// is the "remove after drop" checkbox checked?
if ($('#drop-remove').is(':checked')) {
// if so, remove the element from the "Draggable Events" list
$(this).remove();
}
}
});
</script>
}