How to add js function to jquery calender and dynamic tooltip - javascript

I tried to make some dates highlighted with jquery calender and I did it successfully just for border but I can't for background. But I still don't able to add dynamic tooltip. And I need also to call function on click.
How can I do so (function on click - highlight background - dynamic tooltip "inclined into dates array") ?
$(document).ready(function () {
var disabledDays = ["2017-5-21", "2017-5-24", "2017-5-27", "2017-5-28"];
var tooltip = ["1 tip", "2 tip", "3 tip"];
var date = new Date();
jQuery(document).ready(function() {
$('#datepicker').datepicker({
dateFormat: 'yy-mm-dd',
beforeShowDay: function(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
for (i = 0; i < disabledDays.length; i++) {
if($.inArray(y + '-' + (m+1) + '-' + d,disabledDays) != -1) {
return [1, 'calender_highlight', 'tooltip'];
}
}
return [true];
}
});
});
});
.calender_highlight{
border:2px solid #ffd800;
background-color:#ffd800;
}
.calender_highlight:hover{
border:2px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div id="datepicker"></div>

Because the html for the datepicker is generated dynamically you will have to use the correct event binding, what you are looking for is the .on() functionality of jquery:
$('#datepicker').on('mouseenter','.ui-state-default', function(e) {
$(this).attr('title', 'My tooltip');
});
In that way you will get the browser's default title-style. There is also a bootstrap tooltip function you could consider.

Related

Specific days for datepicker with json?

I have a booking form with specific days and I colored my specific days if you click on my datepicker you will see
so my quesiton is I use array list for my specific
var firstDate = ['2017-06-15'];
var lastDate = ['2017-12-20'];
var availabledays = ['2017-06-15', '2017-06-16', '2017-06-23', '2017-06-30', ];
var booked = ['2017-06-16', '2017-06-23', '2017-06-24', '2017-06-25'];
var ssdays = [];
but I have to use json that's why I created a json file as below
dates.json
{
"firstDate": [
{ "field": "2017-06-15"}
],
"lasDate":[
{"field":"2017-12-20"}
],
"availabledays":[
{"field":"2017-06-15"},
{"field":"2017-06-16"},
{"field":"2017-06-23"},
{"field":"2017-06-30"}
],
"booked":[
{"field":"2017-06-16"},
{"field":"2017-06-23"},
{"field":"2017-06-24"},
{"field":"2017-06-25"}
]
}
and my question is how to request from server mys json files and then put into datepicker when focus?
and this is my datepicker example full demo
$(function() {
var firstDate = ['2017-06-15'];
var lastDate = ['2017-12-20'];
var availabledays = ['2017-06-15','2017-06-16','2017-06-23','2017-06-30',];
var booked = ['2017-06-16','2017-06-23','2017-06-24','2017-06-25'];
var ssdays = [];
var dateFormat = "mm/dd/yy",
from = $("#checkin").datepicker({
changeMonth : true,
numberOfMonths: 2,
firstDay:1,
minDate:new Date(firstDate),
maxDate:new Date(lastDate),
onSelect: function( selectedDate ) {
var newdate = new Date();
var date = $(this).datepicker('getDate');
date.setTime(date.getTime() + (1000*60*60*24))
$( "#checkout" ).datepicker( "option", "minDate",date );
},
beforeShowDay : function(date){
var y = date.getFullYear().toString(); // get full year
var m = (date.getMonth() + 1).toString(); // get month.
var d = date.getDate().toString(); // get Day
if(m.length == 1){ m = '0' + m; } // append zero(0) if single digit
if(d.length == 1){ d = '0' + d; } // append zero(0) if single digit
var currDate = y+'-'+m+'-'+d;
if(jQuery.inArray(currDate,availabledays) >= 0){
return [false, "ui-highlight"];
}
if(jQuery.inArray(currDate,booked) >= 0){
return [true, "ui-bos"];
}else{
return [true];
}
},
isTo1: true,
}).on("change", function() {
to.datepicker("option", "minDate", getDate(this));
}),
to = $("#checkout").datepicker({
changeMonth : true,
changeYear : true,
firstDay:1,
numberOfMonths: 2,
minDate:new Date(firstDate),
maxDate:new Date(lastDate),
onSelect: function( selectedDate ) {
$( "#checkin" ).datepicker( "option", "maxDate", selectedDate );
},
beforeShowDay : function(date){
var y = date.getFullYear().toString(); // get full year
var m = (date.getMonth() + 1).toString(); // get month.
var d = date.getDate().toString(); // get Day
if(m.length == 1){ m = '0' + m; } // append zero(0) if single digit
if(d.length == 1){ d = '0' + d; } // append zero(0) if single digit
var currDate = y+'-'+m+'-'+d;
if(jQuery.inArray(currDate,booked) >= 0){
return [true, "ui-highlight-donus"];
}
if(jQuery.inArray(currDate,availabledays) >= 0){
return [true, "ui-bos"];
}
if(jQuery.inArray(currDate,ssdays) >= 0){
return [true, "ui-ss-donus"];
}else{
return [true];
}
}
}).on("change", function() {
from.datepicker("option", "maxDate", getDate(this));
});
});
.form{
width:960px;
margin:120px auto;
}
.form input{
width:250px;
padding:10px;
}
.ui-highlight .ui-state-default{background: red !important;border-color: red !important;color: white !important; cursor:no-drop;}
.ui-bos .ui-state-default{background: green !important;border-color: green !important;color: white !important;}
.ui-ss .ui-state-default{background: yellow !important;border-color: yellow !important;color: gray !important; cursor:help;}
.ui-ss-donus .ui-state-default{background: yellow !important;border-color: yellow !important;color: gray !important; cursor:help;}
.ui-highlight-donus .ui-state-default{background: red !important;border-color: red !important;color: white !important; }
.ui-testtarih .ui-state-default{
background:black !important;
color:#FFF !important;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
<div class="form">
<input type="text" id="checkin" />
<input type="text" id="checkout" />
<input type="submit" value="Search" />
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
I would disable the datepicker and grey them out while the request is happening and enable them after the request completed. The jquery ui datepicker can be disabled with $('#checkout').datepicker('disable').
As far as the data format, you can write a couple functions to pull that data out in a success callback. Something like
$.ajax({
url: "your-data-url.com"
})
.done(function(serverFormattedDays) {
var availableDays = serverFormattedDays.map(function(day) {
return day.field;
}
// code to create/edit/modify datepickers here.
};
will return the available days in the format you want.

Button to increase date in text box

I am writing following code.
<!doctype html>
<html><head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Icon trigger</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js">
</script> <script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js">
</script>
<script>
$(function () {
$("#datepicker").datepicker({
minDate: -0,
maxDate: "+1M +2D",
showOn: "button",
buttonImage: "calendar.png",
buttonImageOnly: true,
dateFormat: 'D dd MM yy' });
$.datepicker.formatDate('yy-mm-dd');
});
function updateDate(){
var inputDate=document.getElementById('datepicker').value;
var selectedDate=new Date(inputDate);
var today=new Date();
var tomorrow=new Date();
tomorrow.setDate(today.getDate()+1);
selectedDate.setHours(0,0,0,0);
today.setHours(0,0,0,0);
tomorrow.setHours(0,0,0,0);
var DaysFull=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
var DaysShort=["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sun"];
var MonthsFull=["January","February","March","April","May","June","July","August","September","October","November","December","January"];
var MonthsShort=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan"];
var finalDate=DaysShort[selectedDate.getDay()]+" "+selectedDate.getDate()+" "+MonthsFull[selectedDate.getMonth()];
if(selectedDate.getTime() == today.getTime()){
document.getElementById('datepicker').value=finalDate+" (Today)";
}
else if(selectedDate.getTime() == tomorrow.getTime()){document.getElementById('datepicker').value=finalDate+" (Tomorrow)";}
else {document.getElementById('datepicker').value=finalDate;}
}
function addDaysToDate() {
var date1= document.getElementById('datepicker').value;
var date = new Date( Date.parse( date1 ) );
date.setDate( date.getDate() + 1 );
alert(date);
document.getElementById('datepicker').value=date;
}
</script>
</head>
<body>
<form><input type="text" id="datepicker" onchange="javascript:updateDate()" style="width:160px" />
<button onclick="addDaysToDate()">add</button></form>
</body></html>
I have a button on click of which date in text box should be increase by 1 upto next 32 days and not beyong but above code increases the date and value disappears from the text box rather than showing ...
You are setting a date field to set additional text so the date in not a valid date object and break the plugin.
You are using the datepicker plugin so you can use getDate and setDate methods to get/set the values as date objects.
Docs: http://api.jqueryui.com/datepicker/#method-getDate and http://api.jqueryui.com/datepicker/#method-setDate
I changed your code by using an additional field to show if the date is today or tomorrow:
$(function () {
$("#datepicker").datepicker({
minDate: -0,
maxDate: "+1M +2D",
showOn: "button",
buttonImage: "calendar.png",
buttonImageOnly: true,
dateFormat: 'D dd MM yy'
});
$("#datepicker").change(function () {
updateDate();
});
$("#addDate").click(function () {
addDaysToDate();
});
});
function updateDate() {
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate() + 1);
var date2 = $('#datepicker').datepicker('getDate');
date2.setHours(0,0,0,0);
today.setHours(0,0,0,0);
tomorrow.setHours(0,0,0,0);
if (date2.getTime() == today.getTime()) {
$('#todtom').text(" (Today)");
} else if (date2.getTime() == tomorrow.getTime()) {
$('#todtom').text(" (Tomorrow)");
} else {
$('#todtom').text("");
}
}
function addDaysToDate() {
var date2 = $('#datepicker').datepicker('getDate');
date2.setDate(date2.getDate() + 1);
$('#datepicker').datepicker('setDate', date2);
$('#datepicker').change();
}
I changed the code to use full jQuery code not a mix of jQuery and JS for DOM manipulation.
Demo:

How to Apply multiple styles on days

I have to mark three kind of days with different styles: Out_of_window, Free or Unavailable. The unavailable has to be disabled.
I made a function based on this question. And I had to remove the default datepicker class (ui-state-default) otherwise I couldn't change the bg-image.
Everything work as desired, until I change month. When I get back to original month, the day gets back its orignal class (ui-state-default) and I have no more my customized styles according the kind of day.
So, I have the following codes:
var pick_up_out_of_window_dayDates = new Array("2012-12-11","2012-12-12");
var pick_up_free_dayDates = new Array("2012-12-21","2012-12-22");
(as global ones)
function applyDayStyles(date){
var enabled = true;
var cssClass = "";
console.log(date);
var day = date.getDate();
var month = date.getMonth() + 1; //0 - 11
var year = date.getFullYear();
var compare = year + "-" + month + "-" + day;
var pick_up_out_of_window_day = pick_up_out_of_window_dayDates.indexOf(compare) + " " + compare
var pick_up_free_day = pick_up_free_dayDates.indexOf(compare) + " " + compare
if (pick_up_out_of_window_dayDates.indexOf(compare) >= 0){
cssClass = "pick_up_out_of_window_dayCalendar";
console.log(1);
return new Array(enabled, cssClass, pick_up_out_of_window_day);
}
else
if (pick_up_free_dayDates.indexOf(compare) >= 0){
cssClass = "pick_up_free_dayCalendar";
console.log(2);
return new Array(enabled, cssClass, pick_up_free_day);
}
else
return new Array(false, cssClass, date);
}
$(document).ready(function() {
$(".datepicker").datepicker({
minDate: 0,
beforeShowDay: applyDayStyles
})
//{edited}
// this is un necesssary !
// $('.pick_up_free_dayCalendar').children().removeClass('ui-state-default').addClass('pick_up_free_dayCalendarIN'); // I Had to add this line to remove the defaukt bg style.
})
Any thoughts?
Just have to override the default class :
.datepicker .pick_up_out_of_window_dayCalendar .ui-state-default {background: red;}
.datepicker .pick_up_free_dayCalendar .ui-state-default {background: blue;}
Thanx to #adeneo (see questions' coments)
http://jsfiddle.net/Cwg3P/2/

Highlight <TR> entire week datepicker

I have a datepicker that is fully functional and is working whereby you can select an entire commencing working week (Mon-Fri). What I am now trying to do is extend it a little further so that when I click on a specific week. It will highlight that entire . I have it paritally working which looks like the following: Calandar preivew. It can be seen that the problem I am having is that the table row to me seems to be doing a odd, even, odd even. As for the first week I highlight the row is highlighted in red and the cells are hihglighted in yellow. Then the week afer that it work fines and then if I was to select the week after that the same would be repeated. I tried checking the jquery-ui-1.8.4.custom.css and the jquery-ui.css, and had no luck. What seems to confuse me is why are the cells being highlighted in yellow? The code follows for my datepicker.
Javascript:
$(function()
{
var startDate;
var endDate;
var selectCurrentWeek = function()
{
window.setTimeout(function () { $('.week-picker').find('.ui-datepicker-current-day a').addClass('ui-state-active')}, 1);
}
function check(d) {
if(d.length() == 2) {
dd = d;
return dd;
} else {
dd = "0" + myDateParts[0];
return dd;
}
}
var selectedWeek;//remember which week the user selected here
$('.week-picker').datepicker( {
beforeShowDay: $.datepicker.noWeekends,
showOtherMonths: true,
selectOtherMonths: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 1);
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
var dateFormat = 'yy-mm-dd'
var newDate = $('#startDate').text($.datepicker.formatDate( dateFormat, startDate, inst.settings ));
var oldDate = document.getElementById('startDate');
var date_textnode = oldDate.firstChild;
var date_text = date_textnode.data;
myDateParts = date_text.split("-");
var dd = myDateParts[2];
var mm = myDateParts[1];
var yy = myDateParts[0];
selectCurrentWeek();
window.location.href = "/timesheet?week_commencing=" + yy + "-" + mm + "-" + dd;
},
beforeShowDay: function(date) {
var cssClass = '';
if(date >= startDate && date <= endDate)
cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek();
}
});
$( ".week-picker" ).datepicker().click(function(event) {
// highlight the TR
$(".ui-datepicker-current-day").parent().addClass('highlight');
// highlight the TD > A
$(".ui-datepicker-calendarr-day").siblings().find('a').addClass('white');
});
$('.week-picker .ui-datepicker-calendar tr').live('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
$('.week-picker .ui-datepicker-calendar tr').live('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });
});
HTML
<div class="datepicker borderbox">
<b><center>Hours for Week commencing: <span id="startDate"></span></center></b>
<div class="week-picker"></div>
</div>
CSS
.highlight {
border: 1px solid red;
}
.white {
background: white !important;
}
I have tried looking at the following stackoverflow question Related stackoverflow. Had no luck with this, as the link was broken and also tried viewing the it in JSfiddle. Further to this the way I have set my datepicker is different.
I am intially trying to get my calendar to work like this But for some reason when I try do this I get the following. Is this something to do with the css
Update2
Calendar & Firebug output
Is this what you want?
http://jsfiddle.net/william/YQ2Zw/2/
There were a couple of things that went wrong:
The ui-datepicker-current-day class was applied to a <td> element, so it only needs to travel one level up to find the <tr>, so I took away one call to parent():
$(".ui-datepicker-current-day").parent().addClass('highlight');
You set multiple days with the ui-datepicker-current-day class. That was why I needed to use the :eq(0) selector to only select the first element:
$(".ui-datepicker-current-day:eq(0)").siblings().find('a').addClass('white');
Also, you were calling the wrong class for the statement above.

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