Events not showing up in Anglular UI-Calender - javascript

I am trying to use Angular UI Calendar:
http://angular-ui.github.io/ui-calendar/
I implemented all the steps, but my events info coming from API are not getting displayed on calendar.
following is my HTML:
<div class="btn-toolbar">
<div class="btn-group">
<button class="btn btn-success" ng-click="changeView('agendaDay', 'myCalendar1')">Day</button>
<button class="btn btn-success" ng-click="changeView('agendaWeek', 'myCalendar1')">Week</button>
<button class="btn btn-success" ng-click="changeView('month', 'myCalendar1')">Month</button>
</div>
</div>
<div class="calendar" ng-model="eventSources" calendar="myCalendar1" ui-calendar="uiConfig.calendar" ng-click="alertOnEventClick();">
</div>
following is my controller code :
$scope.events=[];
$http.get("/ABC/ABC", {
params: {
"calenderView": 1
}
}).success(function(data, status, headers, config) {
//Declared Array for Data.
for(var i=0; i< data.eventCalender.length; i++){
$scope.events.push = {
title:data.eventCalender[i].title,
start:data.eventCalender[i].start,
end:data.eventCalender[i].end
}
}
}).
error(function(data, status, headers, config) {
SpinnerSvc.hide('globalSpinner');
});
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$scope.changeTo = 'Hungarian';
/* event source that pulls from google.com */
$scope.eventSource = {
className: 'gcal-event', // an option!
currentTimezone: 'America/Chicago' // an option!
};
/* event source that contains custom events on the scope */
/* event source that calls a function on every view switch */
$scope.eventsF = function (start, end, timezone, callback) {
var s = new Date(start).getTime() / 1000;
var e = new Date(end).getTime() / 1000;
var m = new Date(start).getMonth();
var events = [{title: 'Feed Me ' + m,start: s + (50000),end: s + (100000),allDay: false, className: ['customFeed']}];
callback(events);
};
/* alert on eventClick */
$scope.alertOnEventClick = function( date, jsEvent, view){
$scope.alertMessage = ($scope.title + ' was clicked ');
};
/* alert on Drop */
$scope.alertOnDrop = function(event, delta, revertFunc, jsEvent, ui, view){
$scope.alertMessage = ('Event Dropped to make dayDelta ' + delta);
};
/* alert on Resize */
$scope.alertOnResize = function(event, delta, revertFunc, jsEvent, ui, view ){
$scope.alertMessage = ('Event Resized to make dayDelta ' + delta);
};
/* add and removes an event source of choice */
$scope.addRemoveEventSource = function(sources,source) {
var canAdd = 0;
angular.forEach(sources,function(value, key){
if(sources[key] === source){
sources.splice(key,1);
canAdd = 1;
}
});
if(canAdd === 0){
sources.push(source);
}
};
/* add custom event*/
$scope.addEvent = function() {
$scope.events.push({
title: 'Open Sesame',
start: new Date(y, m, 28),
end: new Date(y, m, 29),
className: ['openSesame']
});
};
/* remove event */
$scope.remove = function(index) {
$scope.events.splice(index,1);
};
/* Change View */
$scope.changeView = function(view,calendar) {
uiCalendarConfig.calendars[calendar].fullCalendar('changeView',view);
};
/* Change View */
$scope.renderCalendar = function(calendar) {
$timeout(function() {
if(uiCalendarConfig.calendars[calendar]){
uiCalendarConfig.calendars[calendar].fullCalendar('render');
}
});
};
/* Render Tooltip */
$scope.eventRender = function( event, element, view ) {
element.attr({'tooltip': event.title,
'tooltip-append-to-body': true});
$compile(element)($scope);
};
/* config object */
$scope.uiConfig = {
calendar:{
height: 480,
editable: true,
header:{
left: 'title',
center: '',
right: 'prev,next'
},
eventClick: $scope.alertOnEventClick,
eventDrop: $scope.alertOnDrop,
eventResize: $scope.alertOnResize,
eventRender: $scope.eventRender
}
};
$scope.changeLang = function() {
if($scope.changeTo === 'Hungarian'){
$scope.uiConfig.calendar.dayNames = ["Vasárnap", "Hétfő", "Kedd", "Szerda", "Csütörtök", "Péntek", "Szombat"];
$scope.uiConfig.calendar.dayNamesShort = ["Vas", "Hét", "Kedd", "Sze", "Csüt", "Pén", "Szo"];
$scope.changeTo= 'English';
} else {
$scope.uiConfig.calendar.dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
$scope.uiConfig.calendar.dayNamesShort = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
$scope.changeTo = 'Hungarian';
}
};
/* event sources array*/
$scope.eventSources = [$scope.events, $scope.eventSource, $scope.eventsF];
$scope.eventSources2 = [$scope.calEventsExt, $scope.eventsF, $scope.events];
//}

You have a syntax error when you push new event to $scope.events array. Try this:
...
for(var i=0; i< data.eventCalender.length; i++){
$scope.events.push({
title:data.eventCalender[i].title,
start:data.eventCalender[i].start,
end:data.eventCalender[i].end
});
}
...
Right now you just re-assign array push function to your event object.

Related

FullCalendar events colors

I have a calendar, and outside of this I have a box where I put the event values (client, barber, service and I choose a color). After loading the values, an element is generated that I can select and drag to the calendar. The following happens to me:
When I create an event and drag it to the calendar, it is placed with the color that I configured. If I click the save button, it loads correctly into the database. A json is saved with the event information, for example:
{"id":2,"title":"Maria Marco","barbero":"Diego","servicio":"Corte","start":"2020-03-21T10:30:00","end":"2020-03-21T11:00:00","color":"rgb(0, 86, 179)"}
Suppose I don't have any items in the database, and I create 3 events and drag them to the calendar. If I click the save button, these 3 will be saved correctly as indicated above.
Now if I do a new event load, these new elements will load correctly, but in the previous elements the color property now disappears.
I appreciate if any find the error in this spaghetti of js
$(function() {
var containerEl = document.getElementById('external-events');
var calendarEl = document.getElementById('calendar');
// initialize the external events
// -----------------------------------------------------------------
new FullCalendarInteraction.Draggable(containerEl, {
itemSelector: '.external-event',
eventData: function(eventEl) {
var barbero = $("#barbero").children(".opcion-barbero:selected").html()
var servicio = $("#servicio").val()
return {
title: eventEl.innerText,
extendedProps: { "barbero": barbero, "servicio": servicio, "color": eventEl.style.backgroundColor },
backgroundColor: eventEl.style.backgroundColor,
borderColor: eventEl.style.backgroundColor
};
}
});
view = 'timeGridDay';
header = {
left: 'prev,next timeGridDay,timeGridWeek,dayGridMonth',
center: '',
right: ''
};
var calendar = new FullCalendar.Calendar(calendarEl, {
timeZone: 'local',
plugins: ['interaction', 'dayGrid', 'timeGrid'],
eventSources: [
// your event source
{
url: 'ajax/turnos2.ajax.php'
}
],
editable: true,
droppable: true, // this allows things to be dropped onto the calendar !!!
drop: function(info) {
info.draggedEl.parentNode.removeChild(info.draggedEl);
}
});
calendar.render();
/* ADDING EVENTS */
var currColor = '#3c8dbc' //Red by default
//Color chooser button
var colorChooser = $('#color-chooser-btn')
$('#color-chooser > li > a').click(function(e) {
e.preventDefault()
//Save color
currColor = $(this).css('color')
//Add color effect to button
$('#add-new-event').css({
'background-color': currColor,
'border-color': currColor
})
})
$('#add-new-event').click(function(e) {
e.preventDefault()
//Get value and make sure it is not null
var val = $('#new-event').val()
if (val.length == 0) {
return
}
//Create events
var event = $('<div />')
event.css({
'font-weight': 300,
'background-color': currColor,
'border-color': currColor,
'color': '#fff'
}).addClass('external-event')
event.html(val)
$('#external-events').prepend(event)
//Add draggable funtionality
ini_events(event)
//Remove event from text input
$('#new-event').val('')
})
/*==============================================
Apply changes to the events
==============================================*/
$(document).on("click", "span.guardarCalendario", function() {
var arrayEventos = new Array();
var eventos = calendar.getEvents();
// Contador para ID
var num = 1;
eventos.forEach(e => {
// Nombre del turno
title = (e._def["title"]);
barbero2 = (e._def.extendedProps["barbero"]);
servicio = (e._def.extendedProps["servicio"]);
color = (e._def.extendedProps["color"]);
id = num;
num = num + 1;
var evento = new Object();
evento["id"] = id;
evento["title"] = title;
evento["barbero"] = barbero2;
evento["servicio"] = servicio;
evento["start"] = start;
evento["end"] = end;
evento["color"] = (e._def.extendedProps["color"]);
arrayEventos.push(evento);
})
$("#turnos").val(JSON.stringify(arrayEventos))
var data = { 'data': JSON.stringify(arrayEventos) }
$.ajax({
type: 'POST',
url: 'ajax/turnos.ajax.php',
dataType: 'json',
data: data,
success: function(data, status, xhr) {
alert("response was " + data);
},
error: function(xhr, status, errorMessage) {
$("#debug").append("RESPONSE: " + xhr.responseText + ", error: " + errorMessage);
}
});
})
turnos.ajax.php
<?php
require_once "../modelos/turnos.modelo.php";
require_once "../controladores/turnos.controlador.php";
class AjaxTurnos{
public $data;
public function ajaxActualizarTurnos(){
$datos = ($this->data);
foreach(json_decode($datos) as $value){
$respuesta = ModeloTurnos::mdlActualizarTurnos(json_encode($value).PHP_EOL);
}
return $respuesta;
}
}
/*==============================
ACTUALIZAR TURNOS
==============================*/
if(isset($_POST["data"])){
ModeloTurnos::mdlTruncarTurnos();
$turnos = new AjaxTurnos();
$turnos -> data = $_POST["data"];
$turnos -> ajaxActualizarTurnos();
}
turnos2.ajax.php
<?php
require_once "../modelos/turnos.modelo.php";
require_once "../controladores/turnos.controlador.php";
$data = ControladorTurnos::ctrMostrarTurnos();
$data2 = [];
foreach($data as $key=>$value){
$data2[] = json_decode($value["datos"]);
}
//returns data as JSON format
echo (json_encode($data2));

Need help, want to display different events for each day in fullcalendar

I want to display different event for each day in fullcalendar from a json encoded array.
if employees offday exist display offdays which is coming from another table in json encoded array.
First query return:
"[
{"id":4901,"title":4901,"start":"2018-01-01","end":"2019-04-30"},
{"id":4901,"title":4901,"start":"2018-01-01"
]"
Second query:
"[
{"id":4901,"offday":0},
{"id":4901,"offday":6}
]"
Blade view jquery fulcalendar code:
var emps = {!! $emps !!};
var empsoffdays = {!! $emps_offdays !!};
var startdate = emps[0].start;
var enddate = emps[0].end;
var stdate = new Date(startdate);
var st = stdate.getTime();
var endate = new Date(enddate);
var en = endate.getTime();
//console.log(endate);
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
events: [
{
title : '',
start : startdate,
end :enddate,
allDay : false // will make the time show
}
]
});
$('#calendar').fullCalendar( 'addEventSource',
function(start, end,timezone,callback) {
// When requested, dynamically generate a
// repeatable event for every monday.
var events = [];
var monday = 1;
var one_day = (24 * 60 * 60 * 1000);
for (loop = stdate.getTime();
loop <= endate.getTime();
loop = loop + one_day) {
var column_date = new Date(loop);
if (column_date.getDay() == 1) {
events.push({
title: emps[0].timetable_check_in,
start: startdate,
end: enddate,
allDay: false
});
}
}
callback( events );
}
);
each day should display tile which is timetable timing and offdays should diplay title offday from start date to end date[what i was able to achive][1\

can't drag events in FullCalendar if I hide some dates

I'm using fullcalendar and I'm trying to hide the weeks that come before my starting date.
it works perfectly and but the problem that I can't drag my events anymore.
I don't find another way to do that, and what is the problem in my code.
this is my attempt
$(window).load(function () {
var startDate = $('#start_date').val();
//hide all dates before starting date
$('#save').click(function(){
$(".fc-day").each(function() {
var startTraining = $('#start_date').val();
var tdDate = new Date ($(this).data('date'));
var startDate = new Date (startTraining);
if ((tdDate < startDate) && (($(this).parent().get(0)) !== ($('.fc-day[data-date="' + startTraining + '"]').parent().get(0)))){
$(this).closest('.fc-row').addClass('hidden');
} else {
$(this).closest('.fc-row').removeClass('hidden');
}
});
});
$('#calendar').fullCalendar('gotoDate', startDate);
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var started;
var categoryClass;
var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
right: 'title'
},
selectable: true,
selectHelper: true,
select: function (start, end, allDay) {
$('#fc_create').click();
started = start;
ended = end
$(".antosubmit").on("click", function () {
var title = $("#title").val();
if (end) {
ended = end
}
categoryClass = $("#event_type").val();
if (title) {
calendar.fullCalendar('renderEvent', {
title: title,
start: started,
end: end,
allDay: allDay
},
true // make the event "stick"
);
}
$('#title').val('');
calendar.fullCalendar('unselect');
$('.antoclose').click();
return false;
});
},
eventClick: function (calEvent, jsEvent, view) {
//alert(calEvent.title, jsEvent, view);
$('#fc_edit').click();
$('#title2').val(calEvent.title);
categoryClass = $("#event_type").val();
$(".antosubmit2").on("click", function () {
calEvent.title = $("#title2").val();
calendar.fullCalendar('updateEvent', calEvent);
$('.antoclose2').click();
});
calendar.fullCalendar('unselect');
},
editable: true,
events: [
{
title: 'All Day Event',
start: new Date(y, m, 1)
}, {
title: 'All Day Event',
start: new Date(y, m, 8)
}, {
title: 'All Day Event',
start: new Date(y, m, 15)
}, {
title: 'All Day Event',
start: new Date(y, m, 22)
}, {
title: 'All Day Event',
start: new Date(y, m, 29)
}
]
});
});
<script src="//code.jquery.com/jquery-2.2.3.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.1/moment.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.7.1/fullcalendar.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.7.1/fullcalendar.min.css" rel="stylesheet"/>
<div class="row">
<div class="col-md-6">
<input type="text" value="" id="start_date" placeholder="yyyy-mm-dd">
<button type="button" id="save">Save</button>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="container">
<div id='calendar'></div>
</div>
</div>
</div>
I have found the solution if anyone need this.
$('#save').click(function(){
$(".fc-day").each(function() {
var startTraining = $('#start_date').val();
var tdDate = new Date ($(this).data('date'));
var startDate = new Date (startTraining);
if ((tdDate < startDate) && (($(this).parent().get(0)) !== ($('.fc-day[data-date="' + startTraining + '"]').parent().get(0)))){
$(this).closest('.fc-row').addClass('invisible');
} else {
$(this).closest('.fc-row').removeClass('invisible');
}
});
});
.invisible {
visibility: hidden;
height:0px !important;
min-height:0px !important;
line-height:0px !important
}

Select box to appear inside jQuery Dialog on image click

I am trying to modify this example http://waynegm.github.io/imgNotes/examples/basic_interactive.html#
in order to get a select option to appear inside the dialog box when user clicks on the image. Currently the code places a marker on the area the user selects when in edit mode and opens a dialog box allowing them to enter text, with the options to save / cancel.
Inside the dialog box I want to change the textarea to a select list like:
<select>
<option value="head">Head</option>
<option value="leftarm">Left Arm</option>
<option value="rightarm">Right Arm</option>
<option value="leg">Leg</option>
</select>
It seems like it should be a simple change, I have made others samples where simple on image click makes the drop down appear. But this example has everything else I need like the options to delete and recording the co-ords of the place marker.
The current HTML:
<html>
<head>
<title>jQuery imgNotes - Interactive Base</title>
<style type="text/css" media="all">#import "css/marker.css";</style>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" media="screen">
<script type="text/javascript" src="src/imgNotes.js"></script>
</head>
<body>
<div id="imgdiv" style="text-align: center">
<img id="image" src="image/personsit.jpg" style="border: 30px solid #ccc; padding:20px;" width=400/>
<br/>
<button id="toggleEdit">Edit</button> <button id="export">Export</button>
</div>
<div id=txt></div>
<script type="text/javascript">
;(function($) {
$(document).ready(function() {
var $img = $("#image").imgNotes();
//$img.imgNotes("import", [ {x: "0.5", y:"0.5", note:"AFL Grand Final Trophy"},
// {x: "0.4", y:"0.269", note: "Shoulder"},
// {x: "0.824", y: "0.593", note: "Fluffy microphone"}]);
var $toggle = $("#toggleEdit");
if ($img.imgNotes("option","canEdit")) {
$toggle.text("View");
} else {
$toggle.text("Edit");
}
$toggle.on("click", function() {
var $this = $(this);
if ($this.text()=="Edit") {
$this.text("View");
$img.imgNotes("option", "canEdit", true);
} else {
$this.text('Edit');
$img.imgNotes('option', 'canEdit', false);
}
});
var $export = $("#export");
$export.on("click", function() {
var $table = $("<table/>").addClass("gridtable");
var notes = $img.imgNotes('export');
$table.append("<th>X</th><th>Y</th><th>NOTE</th>");
$.each(notes, function(index, item) {
$table.append("<tr><td>" + item.x + "</td><td>" + item.y + "</td><td>" + item.note + "</td></tr>");
});
$('#txt').html($table);
});
});
})(jQuery);
</script>
</body>
</html>
imgNotes.js file
;(function($) {
$.widget("wgm.imgNotes", {
options: {
zoom: 1,
zoomStep: 0.1,
zoomable: true,
canEdit: false,
vAll: "middle",
hAll: "middle",
/*
* Default callback to create a marker indicating a note location
* See the examples for more elaborate alternatives.
*/
onAdd: function() {
this.options.vAll = "bottom";
this.options.hAll = "middle";
return $(document.createElement('span')).addClass("marker black").html(this.noteCount);
},
/*
* Default callback when the marker is clicked and the widget has canEdit = true
* Opens a dialog with a textarea to write a note.
* See the examples for a more elaborate alternative that includes a WYSIWYG editor
*/
onEdit: function(ev, elem) {
var $elem = $(elem);
$("#dialog-2").remove();
return $('<div id="dialog-2"></div>').dialog({
title: "Body Parts",
resizable: false,
modal: true,
height: "300",
width: "450",
position: { my: "left bottom", at: "right top", of: elem},
buttons: {
"Save": function() {
var txt = $('textarea', this).val();
// Put the editied note back into the data area of the element
// Very important that this step is included in custom callback implementations
$elem.data("note", txt);
$(this).dialog("close");
},
"Delete": function() {
$elem.trigger("remove");
$(this).dialog("close");
},
Cancel: function() {
$(this).dialog("close");
}
},
open: function() {
$(this).css("overflow", "hidden");
var textarea = $('<textarea id="txt" style="height:100%; width:100%;">');
$(this).html(textarea);
// Get the note text and put it into the textarea for editing
textarea.val($elem.data("note"));
}
})
},
/*
* Default callback when the marker is clicked and the widget has canEdit = false
* Opens a dialog displaying the contents of the marker's note
* See examples for alternatives such as using tooltips.
*/
onShow: function(ev, elem) {
var $elem = $(elem);
$('#NoteDialog').remove();
return $('<div id="NoteDialog"></div>').dialog({
modal: false,
resizable: false,
height: 300,
width: 250,
position: { my: "left bottom", at: "right top", of: elem},
buttons: {
"Close" : function() {
$(this).dialog("close");
}
},
open: function() {
// Get the note text and put it into the textarea for editing
$(this).html($elem.data("note"));
$(this).closest(".ui-dialog").find(".ui-dialog-titlebar:first").hide();
},
close: function() {
$(this).dialog("destroy");
}
});
},
/*
* Default callback when the markers are repainted
*/
onUpdateMarker: function(elem) {
var $elem = $(elem);
var $img = $(this.img);
var pos = $img.imgViewer("imgToView", $elem.data("relx"), $elem.data("rely"));
if (pos) {
$elem.css({
left: (pos.x - $elem.data("xOffset")),
top: (pos.y - $elem.data("yOffset")),
position: "absolute"
});
}
},
/*
* Default callback when the image view is repainted
*/
onUpdate: function() {
var self = this;
$.each(this.notes, function() {
self.options.onUpdateMarker.call(self, this);
});
}
},
_create: function() {
var self = this;
if (!this.element.is("img")) {
$.error('imgNotes plugin can only be applied to img elements');
}
// the note/marker elements
self.notes = [];
// the number of notes
self.noteCount = 0;
// the original img element
self.img = self.element[0];
var $img = $(self.img);
// attach the imgViewer plugin for zooming and panning with a custon click and update callbacks
$img.imgViewer({
onClick: function(ev, imgv) {
if (self.options.canEdit) {
ev.preventDefault();
var rpos = imgv.cursorToImg(ev.pageX, ev.pageY);
if (rpos) {
var elem = self.addNote(rpos.x, rpos.y);
self._trigger("onEdit", ev, elem);
}
}
},
onUpdate: function(ev, imgv) {
self.options.zoom = imgv.options.zoom;
self.options.onUpdate.call(self);
},
zoom: self.options.zoom,
zoomStep: self.options.zoomStep,
zoomable: self.options.zoomable
});
$img.imgViewer("update");
},
/*
* Remove the plugin
*/
destroy: function() {
this.clear();
$(this.img).imgViewer("destroy");
$.Widget.prototype.destroy.call(this);
},
_setOption: function(key, value) {
switch(key) {
case 'vAll':
switch(value) {
case 'top': break;
case 'bottom': break;
default: value = 'middle';
}
break;
case 'hAll':
switch(value) {
case 'left': break;
case 'right': break;
default: value = 'middle';
}
break;
}
var version = $.ui.version.split('.');
if (version[0] > 1 || version[1] > 8) {
this._super(key, value);
} else {
$.Widget.prototype._setOption.apply(this, arguments);
}
switch(key) {
case 'zoom':
$(this.img).imgViewer("option", "zoom", value);
break;
case 'zoomStep':
$(this.img).imgViewer("option", "zoomStep", value);
break;
case 'zoomable':
$(this.img).imgViewer("option", "zoomable", value);
break;
}
},
/*
* Pan the view to be centred at the given relative image location
*/
panTo: function(relx, rely) {
return $(this.img).imgViewer("panTo", relx, rely);
},
/*
* Add a note
*/
addNote: function(relx, rely, text) {
var self = this;
this.noteCount++;
var elem = this.options.onAdd.call(this);
var $elem = $(elem);
$(this.img).imgViewer("addElem",elem);
$elem.data("relx", relx).data("rely", rely).data("note", text);
switch (this.options.vAll) {
case "top": $elem.data("yOffset", 0); break;
case "bottom": $elem.data("yOffset", $elem.height()); break;
default: $elem.data("yOffset", Math.round($elem.height()/2));
}
switch (this.options.hAll) {
case "left": $elem.data("xOffset", 0); break;
case "right": $elem.data("xOffset", $elem.width()); break;
default: $elem.data("xOffset", Math.round($elem.width()/2));
}
$elem.click(function(ev) {
ev.preventDefault();
if (self.options.canEdit) {
self._trigger("onEdit", ev, elem);
} else {
self._trigger("onShow", ev, elem);
}
});
$elem.on("remove", function() {
self._delete(elem);
});
this.notes.push(elem);
$(this.img).imgViewer("update");
return elem;
},
/*
* Number of notes
*/
count: function() {
return this.noteCount;
},
/*
* Delete a note
*/
_delete: function(elem) {
this.notes = this.notes.filter(function(v) { return v!== elem; });
$(elem).off();
$(elem).remove();
$(this.img).imgViewer("update");
},
/*
* Clear all notes
*/
clear: function() {
var self = this;
var total = self.notes.length;
for ( var i = 0; i < total; i++ ){
var $this = self.notes[i];
$this.off();
$this.remove();
}
self.notes=[];
self.noteCount = 0;
},
/*
* Add notes from a javascript array
*/
import: function(notes) {
var self = this;
$.each(notes, function() {
self.addNote(this.x, this.y, this.note);
});
$(this.img).imgViewer("update");
},
/*
* Export notes to an array
*/
export: function() {
var notes = [];
$.each(this.notes, function() {
var $elem = $(this);
notes.push({
x: $elem.data("relx"),
y: $elem.data("rely"),
note: $elem.data("note")
});
});
return notes;
}
});
})(jQuery);
I would really appreciate if anyone could help me out.

Events in jQuery UI Datepicker with json data source

I want to display events in the jQuery UI Datepicker. I want the days that have events to be styled differently from days that don't have events, and I want to display a custom tooltip with the event details when hovering dates with events.
The solution to the question "jQuery UI Datepicker with jQuery tipsy" gets very close, but doesn't work with the Datepicker configuration I use. I use the "showOtherMonths" option, and it throws the date link calculation off.
The event data is available at http://mydomain.com/events.json
Mockup of what I want:
This is the code I use for creating the Datepicker:
$('#dateDiv').datepicker({
altField: '#dateInput',
altFormat: 'yy-mm-dd',
dateFormat: 'yy-mm-dd',
firstDay: '1',
showOtherMonths: 'true',
});
I'm not concerned about the CSS part of the solution at this time, just the javascript part. How do I make my custom tooltip appear when hovering the dates with events attached to them? And how do I attach the events (calendar events, not javascript/DOM events ;) )?
This is not a very elegant solution, but it does seem to work. Can someone please come up with something better?
EDIT: Here's a jsFiddle with the code running: http://jsfiddle.net/Tobbe/JrkSN/3/
EDIT2: It works until I click on a date, then all the events disappears because the beforeShowDay callback isn't called in that case. How do I work around that?
getEvents();
$(function() {
$('#dateDiv').datepicker({
altField: '#dateInput',
altFormat: 'yy-mm-dd',
dateFormat: 'yy-mm-dd',
firstDay: '1',
showOtherMonths: 'true',
beforeShowDay: beforeShowDay,
onChangeMonthYear: getEvents
});
});
var enqueuedDates = [];
var tryCounter = 0;
var events = [];
function getEvents() {
events = [];
enqueuedDates = [];
$.getJSON('events.json', function(json) {
events = json;
});
}
function beforeShowDay(date) {
enqueuedDates.push(new Date(date));
if (enqueuedDates.length == 35) {
processEnqueuedDates();
}
return [true, '', ''];
}
function processEnqueuedDates() {
if (!events || events.length === 0) {
tryCounter++;
if (tryCounter < 100) {
setTimeout(processEnqueuedDates, 10);
} else {
tryCounter = 0;
}
return;
}
tryCounter = 0;
for (var i = 0; i < enqueuedDates.length; ++i) {
var event = getEvent(events, enqueuedDates[i]);
if (event) {
var theDateCells = $('#dateDiv .ui-datepicker-calendar td');
var hideTimeoutID;
theDateCells.eq(i).addClass('eventPlanned').
bind('mouseenter', function(eventText) {
return function() {
if (hideTimeoutID) {
clearTimeout(hideTimeoutID);
hideTimeoutID = null;
}
var popup = $('#eventPopup');
if (popup.size() == 0) {
popup = $('<div></div>').attr('id', 'eventPopup');
$('body').append(popup);
}
var pos = $(this).offset();
popup.html('<p>' + eventText + '</p>').
css('left', pos.left + 5 + 'px').
css('top', (pos.top - popup.height() - 2) + 'px').
bind('mouseenter', function() {
clearTimeout(hideTimeoutID);
hideTimeoutID = null;
}).
bind('mouseleave', function() {
$(this).hide();
}).
show();
}
}(event.text)).
bind('mouseleave', function(eventObject) {
hideTimeoutID = setTimeout(function() {
$('#eventPopup').hide();
}, 200);
});
}
}
}
function getEvent(events, date) {
return events.filter(function(event, index, arr) {
return date - $.datepicker.parseDate('yy-mm-dd', event.date) === 0;
})[0];
}

Categories

Resources