renderEvent after selecting dates not working in Fullcalendar - javascript

I would like to add and render event by selection of dates range. select() is correctly fired, but there is error calendar.fullCalendar is not a function on the last line. I googled a lot but did not find any working solution.
I use FullCalendar v4 in timeline-view.
var calendar = null;
document.addEventListener('DOMContentLoaded', function() {
calendar = new FullCalendar.Calendar(document.getElementById('preview'), {
editable: true,
eventResizableFromStart: true,
eventResourceEditable: true,
selectable: true,
...
select: function(selectionInfo) {
var event = new Object();
event.title = 'title';
event.start = selectionInfo.start;
event.end = selectionInfo.end;
event.resourceId = selectionInfo.resource.id;
calendar.fullCalendar('renderEvent', event); // console says 'calendar.fullCalendar is not a function'
//$('#preview').fullCalendar('renderEvent', event); // I also tried this, but the same error as above
}
});
});

calendar.fullCalendar('renderEvent', event);
...I guess you copied this from somewhere? Because this is fullCalendar version 3 syntax. for version 4 you would write
calendar.addEvent(event);
See https://fullcalendar.io/docs/Calendar-addEvent for documentation. Always check that the examples you find apply to the correct version of the software.

Related

fullcalendar: display all events of a specific day when hovering his daycell

I'm developing a Calendar application via fullcalendar.
I'm currently working on a mini sized calendar. The mini calendar will not display the events.
I'm trying to use tooltip instead. so when the user will mouseover a specific daycell - all the events of the specific daycell will be displayed via tooltip. (this is my issue)
I been working on this issue for almost two days now.
unfortunately, full calendar only offers "eventMouseover". (no dayMouseover available).
Also, using $(".fc-day").hover is not really the best way to go because it is working only when hovering the bottom of the cell.
there is no documentation for this on the web so far.
Anybody knows which is the best way to Tackle an issue?
here is my code so far:
$("#miniCalendar").fullCalendar({
defaultDate: currentDate,
viewRender: function (view, element)
{
monthStart = view.intervalStart.format("YYYY-MM-DD");
monthEnd = view.intervalEnd.subtract(1, "days");
monthEnd = view.intervalEnd.format("YYYY-MM-DD");
mStart = view.intervalStart.format("M");
yStart = view.intervalStart.format("YYYY");
},
events: function (start, end, timezone, callback) { //custom events function to be called every time the view changes
$.ajax({
url: getMonthDataUrl,
type: "post",
data: {
startDate: monthStart,
endDate: monthEnd,
custom_config: Config
},
error: function () {
//alert("there was an error while fetching events!");
},
success: function (data) {
calendarData = data;
console.log(calendarData);
thingsToDoAfterWeLoadCalendarData(calendarData);
callback(eventsJsonArray); //pass the event data to fullCalendar via the supplied callback function
}
});
},
fixedWeekCount: false,
dayRender:
function (date, cell) {
//the events are loaded vie eventAfterAllRender function
//eventAfterAllRender takes time to load. so we need dayRender function in order to give the calendar default colors until the real colors are loaded
// the default colors spouse to look like the correct colors. this is needed for a better looking calendar while loading new events
if (!cell.hasClass("fc-other-month")) {
//that means this is a cell of this current month (becuase only cells that belong to other month have the "fc-other-month" class
var weekDay = date.format("dddd");
if (weekDay == "Saturday" || weekDay == "Friday") {
cell.css("background-color", "#edf5f9");
} else{
//regular days
cell.css("background-color", "#f7fafc");
}
} else{
//cells that belong to the other months
$(".fc-other-month").css("background-color", "#ffffff");
}
},
eventAfterAllRender:
(function(view, event, element) {
let viewDisplay = $("#miniCalendar").fullCalendar("getView");
if (viewDisplay.name == "month") { //checking if this the month view. this is needed for better display of the week\day view (if we ever want to use it)
$(".fc-day:not(.fc-other-month)").each(function(index, element) {
//loop through each current month day cell
$(this).empty(); //removing old icons in case they are displayed
let cellDate = moment($(this).data("date")).format("YYYY-M-D"); // "YYYY-M-D" date format is the key in the json_backgrundColorBigCalendar array
$(this).css("background-color", json_backgrundColorBigCalendar[cellDate]); //set the background colour of the cell from the json_backgrundColorBigCalendar array.
});
}
$(".fc-other-month").css("background-color", "#ffffff"); //days that belong to other month gets a color background that will show this days are irrelevant
}),
dayClick: function(date, jsEvent, view) {
window.location = fullCalendarUrl;
},
});
I dont really know if there is a "fullcalendar-way" doing this, but why can't you use your hover event listener and just also let it listen on fc-day-top hover?
$(".fc-day, .fc-day-top").hover(function(e) {
console.log($(e.currentTarget).data("date"));
});
This will also work if you hover the top of a day cell.
Update:
To get the events on hover use this:
var $calendar = $("#calendar");
$(".fc-day, .fc-day-top").hover(function(e) {
var date = moment.utc($(e.currentTarget).data("date"));
var events = $calendar.fullCalendar("clientEvents", function(event) { return event.start.startOf("day").isSame(date); });
console.log(events);
});
(Tested on the calendar on the fullcalendar main site).
Of course you have to change the jQuery selector of the calendar (#calendar) as it is in your code.
I've never seen full calendar before, but if I understand correctly you want to bind a hover function to custom days of the calendar. Is that correct?
If so you can simply select days of the calendar with their "data-date" attribute. So something like the code below would let you specify a hover function for a desired day:
$("[data-date='2017-10-10']").hover(function(e) {
console.log("You moused over 10/10/2017!");
});

How can I set up rule for selectable FullCalendar

I am trying to set up a rule for selectable attribute. The rule should be like this:
selectable attribute is true for future weeks, otherwise false
However, I could not find how can I check dates in calendar option. I tried some ways but javascript does not accept these ways. Here is my current option. Any helps ?
$(document).ready(function () {
$('#calendar').fullCalendar({
//some options
//some options
selectable: true,
selectHelper: true,
select: function (start, end) {
var title = loadRequired("ff8081815c776701015c7788151d06b4",
"activity",
"#Session["token"].ToString()");
var eventData;
if (title) {
eventData = {
title: title,
start: start,
end: end
};
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
}
$('#calendar').fullCalendar('unselect');
},
});
});
I could be mistaken but because selectable is just a bool and doesn't accept a callback I don't think there is a nice way of doing this. I would probably set it to true and then catch it in the select callback.
In the select callback you could check if the selected date is in the future and if it is just call unselect and return from the function.
You can do either/both of these:
1) In the "select" callback, check the start/end dates. If they're before the date that you want to allow, then don't continue to process the code, just return false.
2) You could also set the validRange property so that events can't even be dragged onto the areas you choose to exclude: https://fullcalendar.io/docs/current_date/validRange/
I checked situation on select atrr.
select: function (start, end) {
var check = end.unix()*1000;
var today = #weekdays[6]*1;
if(today > check)
{
$('#calendar').fullCalendar('unselect');
}else
{
$('#calendar').fullCalendar('select');
var title = loadRequired("ff8081815c776701015c7788151d06b4",
"activity",
"#Session["token"].ToString()");
var eventData;
if (title) {
eventData = {
title: title,
start: start,
end: end
};
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
}
}
},
now I can do what I want on functionality. However, I can still select the area on calendar, the area's color changed to blue, then it goes my check point, and if situation is false: unselect atrr is activated.
Is there any way to do this ? Actually selectable attribute should not be true when the area is in the past and should be true on future weeks

eventRender callback renders all events, how to render only a single event

So I am simply adding an event (created a json for it with id, start, etc.)
I tried the following:
$('#calendar').fullCalendar('renderEvent', my_event);
$('#calendar').fullCalendar('updateEvent', my_event);
These make a callback as following:
eventRender: function(event, element) {
console.log('in event Render callback');
console.log(event);
}
eventRender renders all the events in the calendar when adding a single event. So I can see my added event on the calendar immediately, and the 2 console log statements are printed for all events including the new one.
How can I add only this new event (with a new id) on the calendar such that only this new event is rendered (eventRender callback for only new event) and not all the events?
I'm afraid it is not possible by default. You can try to do something like this:
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#button_id').click(function() {
var newEvent = {
title: 'NEW EVENT',
start: new Date(y, m, d),
render: true
};
$('#calendar').fullCalendar('renderEvent', newEvent, 'stick');
});
$('#calendar').fullCalendar({
editable: true,
eventRender: function(event, element) {
if (event.render) {
element.addClass('test');
}
event.render = false;
}
});
});
Code above will add "test" css class to the last added event only. Maybe this will help you somehow.
Fiddle

selecting a day from UICalendar

I am fairly new to angular I am trying to implement a calendar using ui-calendar. So far I have been able to display a very basic calendar and some events on it.
Now I need to be able to click on a day and display the detailed events on a side tab. I seem to be lost on how to achieve this clicking day thing. This may seems very naive, I thought i'd find the html for each day cell on the calendar, and then it would be as easy as attaching a ng-click to it. But I cant seem to find any template where the html for calendar is. All I can see is the directive, which doesnt help much. I dont understand jquery at all, so I am really struggling to find any answers too.
To sum things up, I just want to know how to make a day on calendar clickable.
Thanks in advance.
code:
$scope.uiConfig = {
calendar: {
height: 450,
editable: true,
header: {
left: 'title',
center: '',
right: 'today prev,next'
},
eventClick: $scope.alertOnEventClick,
eventDrop: $scope.alertOnDrop,
eventResize: $scope.alertOnResize,
eventRender: $scope.eventRender,
dayClick: function(date, jsEvent, view) {
console.log("inside dayClick");
alert('Clicked on: ' + date.format());
var events = myCalendar.fullCalendar('clientEvents', function(event) {
return event.start.isSame(date) || event.end.isSame(date) || date.isBetween(event.start, event.end); // Will return all events starting/ending on this date or overlapping this date
});
}
}
};
In your configuration variable you can add a dayClick callback , in this callback you can do something like this:
dayClick: function( date, jsEvent, view ) {
var events = myCalendar.fullCalendar('clientEvents', function(event) {
return event.start.isSame(date) || event.end.isSame(date) || date.isBetween(event.start, event.end); // Will return all events starting/ending on this date or overlapping this date
});
}
This will return all the events that either are on this day or overlap it.
FullCalendar docs can be found here.

Bootstrap Datepicker on change firing 3 times

Hi I have been trying to just get the date of a bootstrap date picker and have been able to but it seems to fires 3 times. NOTE: This is not jquery date picker but bootstrap date picker.
Using this date picker: https://github.com/eternicode/bootstrap-datepicker, not older eyecon.ro one.
$(".date-picker").on("change", function(e) {
contents = $(this).val();
id = $(this).attr('id');
console.log("onchange contents: " + contents);
console.log("onchange id: " + id);
});
HTML:
<input id="start_date" type="text" data-date-format="yyyy-mm-dd" class="date-picker form-control" />
I have used a few other options other than change, like
$('.date-picker').datepicker().change(function(){};
But this does not close date picker, hoping there is an easy solution to this. thx
You should be using the "changeDate" event. For example:
var datePicker = $('.date-picker').datePicker().on('changeDate', function(ev) {
//Functionality to be called whenever the date is changed
});
Please view the documentation here for more info on this event.
it does not fix the problem, but i was using the datepicker to send through an ajax post, so the 3 change events was causing me problems - the 3rd event always failed. even if the documentation says to use a changeDate event, it doesn't seem right to me to fire the input tag's change event 3 times. the value isn't changing 3 times!
I wrote a simple 'debounce' function to get around the problem. doesn't fix the issue - which is due to multiple change events being fired from the methods: setValue (line 508) _setDate:(line 1048) and setValue (line 508) (version 1.3.0) of the widget.
var lastJQueryTS = 0 ;// this is a global variable.
....
// in the change event handler...
var send = true;
if (typeof(event) == 'object'){
if (event.timeStamp - lastJQueryTS < 300){
send = false;
}
lastJQueryTS = event.timeStamp;
}
if (send){
post_values(this);
}
it is pretty simple, just finds the jquery 'event', and makes sure that values in a window of 300ms are ignored. in my testing this all happened in 30 msec or so.
As some has mentioned already, use this:
$('#calendar').on("changeDate", function() {
});
The trick is to use changeDate instead of change.
It seems as if when checking the change event, if the change was from actual user interaction, the change event contains a value for originalEvent.
The event does NOT contain this value if the input was changed via JS:
$obj.val('1990-03-07').change() and the same with bootstrap-datepicker
Here's how I set it up:
Generic initial setup
// General selector for date inputs
var $obj = $('input[type="date"]');
$obj.datepicker({
// options here, not important for this example
});
Handle bootstrap-datepicker specific changes
$obj.datepicker().on('changeDate', function (event) {
handleInputDateAndTimeChange(event);
});
Now, deal with user interaction changes
$('input[type="date"], input[type="time"]').change(function (event) {
// This checks if change was initiated by user input and NOT JS
if(event.originalEvent !== undefined) {
handleInputDateAndTimeChange(event);
}
});
And finally, here's the handleInputDateAndTimeChange function
function handleInputDateAndTimeChange(event) {
var $input = $(event.target);
// Do what you want with $input object here...
}
I tried the answer from #pgee70 and it doesn't work for me. So this is my solution, hope its help
var send=true;
$('.input-group.date').datepicker({
todayBtn: "linked",
keyboardNavigation: false,
forceParse: false,
language: 'es-ES',
weekStart: 1,
format: 'dd/mm/yyyy',
enableOnReadonly:false,
calendarWeeks: true,
autoclose: true,
todayHighlight:true
}).on("changeDate", function(e) {
if(send){
modificarFechaAplicacionCliente($("#input_filtro_fecha_cliente").val());
send=false;
}
setTimeout(function(){send=true;},200);
});
It´s not a beaty solution, but it´s work.
Similar to the above answer, but you should use datepicker unless you've renamed the function:
var datePicker = $('.date-picker').datepicker().on('changeDate', function(ev) {
//Functionality to be called whenever the date is changed
});
This works for me, except in my case, I renamed the function to datepickerBootstrap to avoid the clash with JQuery's. So then it would become:
var datePicker = $('.date-picker').datepickerBootstrap().on('changeDate', function(ev) {
// On change functionality
});
It is fixed find your fixed js datepicker file HERE
Read fixing description HERE
I have faced the same problem with bootstrap-datepicker when it used with the jQuery OnChange event they call function 3 times. Here is my code
#Html.TextBoxFor(x => x.CmpStartDate, "{0:dd-MMM-yyyy}", new { #size = "30", #class = "form-control search-date", #placeholder = "Start date" })
#Html.TextBoxFor(x => x.CmpEndDate, "{0:dd-MMM-yyyy}", new { #size = "30", #class = "form-control search-date", #placeholder = "End date" })
<script>
$('#CmpStartDate,#CmpEndDate').datepicker({
autoclose: true,
todayHighlight: true,
minViewMode: 3,
format: "dd-M-yyyy"
});
$(".search-date").on("change", function () {
cmpStartDate = $("#CmpStartDate").val();
cmpEndDate = $("#CmpEndDate").val();
SearchThisDateRecords(cmpStartDate,cmpEndDate);
});
function SearchThisDateRecords(cmpStartDate,cmpEndDate) {
console.log("Call search method");
}
</script>
We need to call this function only one time, Not multiple time so you can use the below logic to fix this problem
<script>
$('#CmpStartDate,#CmpEndDate').datepicker({
autoclose: true,
todayHighlight: true,
minViewMode: 3,
format: "dd-M-yyyy"
});
var i = 0;
$(".search-date").on("change", function () {
cmpStartDate = $("#CmpStartDate").val();
cmpEndDate = $("#CmpEndDate").val();
SearchThisDateRecords(cmpStartDate,cmpEndDate);
i++;
console.log(i);
if (i == 3) {
SearchThisDateRecords(cmpStartDate,cmpEndDate);
}
});
function SearchThisDateRecords(cmpStartDate,cmpEndDate) {
i =0; //Reset i value
console.log("Call search method");
}
</script>
Get global variable count and check if equal to 0 then execute Your function.
var count=0;
$( "#Id" ).datepicker({ minDate: 0}).on('change',function (){
if(count==0)
validity();//any function
count=1;
});
validity(){ count=0;}
bit annoying..
my code was:
var c=0;var send=false;
$(document).ready(function() {
jQuery( ".ed" ).datepicker({
format: "yyyy-mm-dd",
autoclose:!0
}).on('change',function() {
if(c==2){
c=0;
send=true;
}else{
c++;
send=false;
}
});
});
Please use changeDate function in place of change .
var LastController =['id','value']; //global variable...
function datepeakerchange(e){
if ((LastController[0] != e.target.id && LastController[1] != e.target.value) || (LastController[0] == e.target.id && LastController[1] != e.target.value)) {
LastController[0] = e.target.id;
LastController[1] = e.target.value;
write your code....
}
}
var pickerFireCount = 0;
function checkSelectedDateIsHollyday(rId) {
pickerFireCount++;
if (pickerFireCount == 3) {
if (!selectedDateIsHolyday(rId)) {
showInfoMessage('The date you selected is a holiday.');
pickerFireCount = 0;
}
}
}

Categories