I am trying to calculate the end time of an appointmnent. I am using pickatime and pickadate by amsul and I combined the the two values to one.
$(document).ready(function(){
var datepicker = $('#date').pickadate({
container: '#outlet',
onSet: function(item) {
if ( 'select' in item ) setTimeout( timepicker.open, 0 )
}
}).pickadate('picker')
var timepicker = $('#time').pickatime({
container: '#outlet',
onRender: function() {
$('<button>back to date</button>').
on('click', function() {
timepicker.close()
datepicker.open()
}).prependTo( this.$root.find('.picker__box') )
},
onSet: function(item) {
if ( 'select' in item ) setTimeout( function() {
$datetime.
off('focus').
val( datepicker.get() + ' ' + timepicker.get() ).
focus().
on('focus', datepicker.open)
}, 0 )
}
}).pickatime('picker')
var $datetime = $('#datetime').
on('focus', datepicker.open).
on('click', function(event) { event.stopPropagation(); datepicker.open() })
What I am tryig to do is adding the duration time to the date and time was picked for the end date. I tried to use getHours and setHours but It is not working.
var sart_time = $('#datetime').val()
I need to do somting like this
var end_time = $('#datetime').val()+duration
I have solved the problem by using momentjs. Here is the code just in case someone came across similar issue.
var booking_start = $('#datetime').val()
var booking_end = moment(booking_time).add(**duration**, 'hours').format('LLL')
duration is a var
Related
Is there a way to change the start time of an Event, wich I draged into the calendar.
The Event comes from an external Source like this:
//initialize the external events
$('#external-events .fc-event').each(function() {
/* // store data so the calendar knows to render an event upon drop
$(this).data('event', {
title: $.trim($(this).text()), // use the element's text as the event title
stick: true // maintain when user navigates (see docs on the renderEvent method)
});
*/
var eventObject = {
title: $.trim($(this).text()), // use the element's text as the event title
id: $(this).data('id')
};
// 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
});
});
I want to change/update the start Time and Title - if necessary - of the Event in a modal Dialog. It seems to work fine, but everytime I add another Event by dragging and want to change it, it changes all other dragged Events, too.
eventClick: function(calEvent, jsEvent, view) {
//Sending data to modal:
$('#modal').modal('show');
$("#input_title").val(calEvent.title);
var my_time = moment(calEvent.start).format('LT');
$("#input_time").val(my_time);
var my_date = moment(calEvent.start).format("YYYY-MM-DD");
$("#input_date").val(my_date);
// waiting for button 'save' click:
$('.btn-primary').on('click', function (myEvent) {
calEvent.title = $("#input_title").val();
var my_input_time = $("#input_time").val();
var momentTimeObj = moment(my_input_time, 'HH:mm:ss');
var momentTimeString = momentTimeObj.format('HH:mm:ss');
var my_input_date = $("#input_date").val();
var momentDateObj = moment(my_input_date, 'YYYY-MM-DD');
var momentDateString = momentDateObj.format('YYYY-MM-DD');
calEvent.start = moment(momentDateString + ' ' + momentTimeString, "YYYY-MM-DD HH:mm");
$('#calendar').fullCalendar('updateEvent', calEvent);
$('#calendar').fullCalendar('unselect');
$('#modal').modal('hide');
});
}
What I am doing wrong?
I finally figured out, how to do this. In my example I'm able to change the event end-time by calculating the duration between start and end and diplay it as HH:mm. So the User can change the duration like 01:00 (hour). Also I add some additional fields like "information" and "color". After the changes in a modal (bootstrap) are made, I write it back to the calendar. Maybe there are better solutions for this, but for me it works fine.
// initialize the external events
$('#external-events .fc-event').each(function() {
// Start Time: String to Date
var my_start_time = new Date (new Date().toDateString() + ' ' + $(this).data('start'));
var start_time = moment(my_start_time).toDate();
// End Time: String to Date -> Date to Decimal
var my_dur_time = new Date (new Date().toDateString() + ' ' + $(this).data('duration'));
var dur_time = moment(my_dur_time).format('HH:mm');
dur_time = moment.duration(dur_time).asHours();
//Add Decimal End Time to Start Time
var end_time = moment(start_time).add(dur_time, 'hours');
// store data so the calendar knows to render an event upon drop
$(this).data('event', {
start: $(this).data('start'),
end: end_time,
title: $.trim($(this).text()), // use the element's text as the event title
stick: true, // maintain when user navigates (see docs on the renderEvent method)
});
// 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
});
});
$('#calendar').fullCalendar({
//Other calendar settings here ...
eventClick: function(event, element) {
curr_event = event;
var inp_start_time = moment(event.start).format();
var inp_end_time = moment(event.end).format();
var diff_time = moment(moment(inp_end_time),'mm').diff(moment(inp_start_time),'mm');
diff_time = moment.duration(diff_time, "milliseconds");
diff_time = moment.utc(moment.duration(diff_time).asMilliseconds()).format("HH:mm");
var my_time = moment(event.start).format('HH:mm');
var my_date = moment(event.start).format('DD.MM.YYYY');
var my_hidden_date = moment(event.start).format('YYYY-MM-DD');
$("#inp_time").val(my_time);
$("#inp_date").val(my_date);
$("#inp_hidden_date").val(my_hidden_date);
$("#inp_title").val(event.title);
$("#inp_duration").val(diff_time);
$("#inp_information").val(event.information);
$("#inp_color").val(event.color);
$('#modal').modal('show');
}
});
$("#button_ok").click(function (myevent) {
var my_input_time = $("#inp_time").val();
var momentTimeObj = moment(my_input_time, 'HH:mm:ss');
var momentTimeString = momentTimeObj.format('HH:mm:ss');
var my_input_date = $("#inp_hidden_date").val();
var momentDateObj = moment(my_input_date, 'YYYY-MM-DD');
var momentDateString = momentDateObj.format('YYYY-MM-DD');
var datetime = moment(momentDateString + ' ' + momentTimeString, "YYYY-MM-DD HH:mm");
var my_title = $("#inp_title").val();
var my_duration = $("#inp_duration").val();
var new_dur_time = moment.duration(my_duration).asHours();
//Add Decimal End Time to Start Time
var new_end_time = moment(datetime).add(new_dur_time, 'hours');
var new_information = $("#inp_information").val();
var new_color = $("#inp_color").val();
$.extend(curr_event, {
title: my_title,
start: datetime,
end: new_end_time,
information: new_information,
color: new_color
});
$("#calendar").fullCalendar('updateEvent', curr_event);
});
});
Hope this helps.
Greetings.
Everything was working fine on home page: http://kikidesign.net/dev/mcdowell/, especially the stores section and the opening hours in the footer at the bottom. However, when I went to the http://kikidesign.net/dev/mcdowell/stores/, the stores were not loading. It means that the javascript for this stores are not loading. But when I checked the console log, it shows that the javascript file are there and I found out that when I take out the other javascript file (the opening hours.js), it loads fine but when I put it back, the stores doesn't load. I don't understand why both files were working fine on the home page but no so on the stores page. How do I fix it? I even combined two files together and it loads fine on the home page but not so on the store page. Additionally, the stores section has mixitup plugin with jquery.mixitup.min.js.
Stores files
jquery-custom-scripts.js
( function( $ ) {
$( document ).ready(function() {
var dropdownFilter = {
// Declare any variables we will need as properties of the object
$filters: null,
$reset: null,
groups: [],
outputArray: [],
outputString: '',
// The "init" method will run on document ready and cache any jQuery objects we will need.
init: function(){
var self = this; // As a best practice, in each method we will asign "this" to the variable "self" so that it remains scope-agnostic. We will use it to refer to the parent "dropdownFilter" object so that we can share methods and properties between all parts of the object.
self.$filters = $('#Filters');
self.$reset = $('#Reset');
self.$container = $('#isotope-list');
self.$filters.find('fieldset').each(function(){
var $this = $(this);
self.groups.push({
$buttons : $this.find('.filter'),
$inputsSelect : $this.find('select'),
$inputsText : $this.find('input[type="text"]'),
active : ''
});
});
self.bindHandlers();
},
// The "bindHandlers" method will listen for whenever a select is changed.
bindHandlers: function(){
var self = this;
// Handle select change
self.$filters.on('click', '.filter', function(e){
e.preventDefault();
var $button = $(this);
// If the button is active, remove the active class, else make active and deactivate others.
$button.hasClass('active2') ?
$button.removeClass('active2') :
$button.addClass('active2').siblings('.filter').removeClass('active2');
self.parseFilters();
});
// Handle dropdown change
self.$filters.on('change', function(){
self.parseFilters();
});
// Handle key up on inputs
self.$filters.on('keyup', 'input[type="text"]', function() {
var $input = $(this);
console.log($input.val());
$input.attr('data-filter', '[class*="'+$input.val().replace(/ /, '-')+'"]');
if ($input.val() == '')
$input.attr('data-filter', '');
console.log($input.attr('data-filter'));
self.parseFilters();
});
// Handle reset click
self.$reset.on('click', function(e){
e.preventDefault();
self.$filters.find('.filter').removeClass('active2');
self.$filters.find('.show-all').addClass('active2');
self.$filters.find('select').val('');
self.$filters.find('input[type="text"]').val('').attr('data-filter', '');
self.parseFilters();
});
},
// The parseFilters method pulls the value of each active select option
parseFilters: function(){
var self = this;
// loop through each filter group and grap the value from each one.
for(var i = 0, group; group = self.groups[i]; i++){
var activeButtons = group.$buttons.length ? group.$buttons.filter('.active2').attr('data-filter') || '' : '';
var activeSelect = group.$inputsSelect.length ? group.$inputsSelect.val() || '' : '';
var activeText = group.$inputsText.length ? group.$inputsText.attr('data-filter') : '';
group.active = activeButtons+activeSelect+activeText;
console.log(group.active);
}
self.concatenate();
},
// The "concatenate" method will crawl through each group, concatenating filters as desired:
concatenate: function(){
var self = this;
self.outputString = ''; // Reset output string
for(var i = 0, group; group = self.groups[i]; i++){
self.outputString += group.active;
}
// If the output string is empty, show all rather than none:
!self.outputString.length && (self.outputString = 'all');
console.log(self.outputString);
// ^ we can check the console here to take a look at the filter string that is produced
// Send the output string to MixItUp via the 'filter' method:
if(self.$container.mixItUp('isLoaded')){
self.$container.mixItUp('filter', self.outputString);
}
}
};
// On document ready, initialise our code.
$(function(){
// Initialize dropdownFilter code
dropdownFilter.init();
// Instantiate MixItUp
$('#isotope-list').mixItUp({
controls: {
enable: false // we won't be needing these
},
callbacks: {
onMixFail: function(){
alert('No items were found matching the selected filters.');
}
}
});
});
$('.btn-clear').on('click', function(event) {
event.preventDefault();
$(this).prev().val("").change();
});
$('select').change(function() {
if ($(this).val() == "") {
$(this).next().hide('.btn-hide');
} else {
$(this).next().show('.btn-hide');
}
});
});
} )( jQuery );
Opening hours js file
( function( $ ) {
$( document ).ready(function() {
var currentDate = new Date();
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Weekday";
weekday[2] = "Weekday";
weekday[3] = "Weekday";
weekday[4] = "Weekday";
weekday[5] = "Weekday";
weekday[6] = "Saturday";
var currentDay = weekday[currentDate.getDay()];
var currentDayID = "#" + currentDay; //gets todays weekday and turns it into id
$(currentDayID).toggleClass("today"); //this works at hightlighting today
});
$( document ).ready(function() {
var dayOfWeek = (new Date).getDay();
var hours = ["Today: 9:00am to 6:00pm", // Sunday
"Today: 8:00am to 9:00pm", // Monday
"Today: 8:00am to 9:00pm", // Tuesday
"Today: 8:00am to 9:00pm", // Wednesday
"Today: 8:00am to 9:00pm", // Thursday
"Today: 8:00am to 9:00pm", // Friday
"Today: 8:00am to 5:00pm"]; // Saturday
var todaysHours = hours[dayOfWeek];
document.getElementById("hours").innerHTML = todaysHours;
});
} )( jQuery );
Console is giving you the error of your code:
Uncaught TypeError: Cannot set property 'innerHTML' of null
As you're trying to do at line 212:
document.getElementById("hours").innerHTML = todaysHours;
Are you sure that #hours element exist? I can't find it in your HTML, so you're trying to do something with an element that doesn't exist.
You should do in order to avoid that problem:
var DOMhours = document.getElementById("hours")
if (DOMhours) DOMhours.innerHTML = todaysHours
If you want to do that after the stores are loaded, you should be sure that the stores are loaded and, after the stores are loaded and you've appended them to the HTML, get the #hours element and put the innerHTML that you want. But always is a good idea to check before if the element is there to avoid those errors. :)
You are trying to set the property of a DOM element that doesn't exist.
Line 212:
document.getElementById("hours").innerHTML = todaysHours;
You can check the browser's console for errors like these by pressing F12.
I'm trying to make a simple calculator for rent arrears, so that as soon as the user types in their values, the "results" section of the table will auto-fill with their results.
At the moment when the user fills in their details, the results section just remains as it was before; however when I de-bug the code, it tells me that there are no errors. I'm pretty sure that the problem is in my event handlers, but I can't work out where/why.
Here is the code:
$(document).ready(function () {
$("#date1").datepicker({
}).on("change", function (e) {
dataBind();
});
$("#date2").datepicker({
}).on("change", function (e) {
dataBind();
});
$(document).on("change", "table input", function () {
dataBind();
});
$("#r1").click(function () {
dataBind();
});
$("#r2").click(function () {
dataBind();
});
$("#r3").click(function () {
dataBind();
});
});
Where date1 and date2 are datepickers, and r1, r2, and r3 are radio buttons.
dataBind is a function which carries out the calculations and updates the results field:
var dataBind = function () {
var config = {
dueDate: new Date($('#date1').val()),
untilDate: new Date($('#date2').val()),
rentAmount: $('#rentAmount').val(),
dueDateResult: $('#date1'),
calcUntilResult: $('#date2')
};
t = new workings(config);
$("#dueDateFirstMissed").html(t.dueDateFirstPaymentResult);
$("#untilDateCalculate").html((t.calculatedUntil));
$("#numberDays").html(t.numberDays.toFixed(0));
$("#numberperiods").html((t.numberPeriods));
$("#amountDue").html("£" + (t.amountDue.toFixed(2)));
$("#dailyRate").html("£" + ((t.dailyRate).toFixed(2)));
};
Here is a link to the fiddle although bear in mind that I haven't finished writing the calculations!
Any help/pointers would be so gratefully appreciated!
Thanks in advance
In your JSFiddle, you have a typo in your getNumberPeriods function, where firsyDate.getMonth() should be firstDate.getMonth(). Rectifying this seems to resolve the issue.
As a sidenote, I would also keep in mind the possibility that someone enter a value that isn't a number in your "Amount of rent due" field. Doing so currently yields NaN in your UI.
Good luck!
There was a syntax error in your variable assigned in below function
function getNumberPeriods() {
var periodLength = getPeriodLength();
var calcDate = (options.untilDate);
var calcYear = calcDate.getFullYear();
var calcMonth = calcDate.getMonth();
var calcDay = calcDate.getDate();
var firstDate = (options.dueDate);
var firstYear = firstDate.getFullYear();
var firstMonth = firstDate.getMonth(); //this was firsyDate.getMonth()
var firstDay = firstDate.getDate();
.....
}
DEMO
UPDATE
You can change your values when you fill all the 3 fields or else you will get NaN in your result and you can do it as below:
var dataBind = function () {
if($("#date1").val()!="" && $("#date2").val()!="" && $('#rentAmount').val()!="")
{ //If all the fields have values then get it done
var config = {
dueDate: new Date($('#date1').val()),
untilDate: new Date($('#date2').val()),
rentAmount: $('#rentAmount').val(),
dueDateResult: $('#date1'),
calcUntilResult: $('#date2')
};
console.log(config);
t = new workings(config);
$("#dueDateFirstMissed").html(t.dueDateFirstPaymentResult);
$("#untilDateCalculate").html((t.calculatedUntil));
$("#numberDays").html(t.numberDays.toFixed(0));
$("#numberperiods").html((t.numberPeriods));
$("#amountDue").html("£" + (t.amountDue.toFixed(2)));
$("#dailyRate").html("£" + ((t.dailyRate).toFixed(2)));
}
};
Note : You haven't given id to your rentAmount textbox at top Just add it too
Updated demo
I am using Isotopes (v1) and have created a search field following an example in a Pen.
Initially it works, however, if I filter the Isotope gallery then the search field stops working.
I believe the search function still runs just doesn't filter the gallery and I am unsure how to fix the problem. In fact I am unsure what the exact problem is as no errors are thrown.
Here is a Fiddle with a working example.
Here is the search, filter and isotope JavaScript:
var $container = $('.isotope'),
qsRegex,
filters = {};
$container.isotope({
itemSelector : '.element',
masonry : {
columnWidth : 120
},
getSortData : {
name : function ( $elem ) {
return $elem.find('.name').text();
}
},
filter: function() {
return qsRegex ? $(this).text().match( qsRegex ) : true;
}
});
function searchFilter() {
qsRegex = new RegExp( $quicksearch.val(), 'gi' );
$container.isotope();
}
// use value of search field to filter
var $quicksearch = $('#quicksearch').keyup( debounce( searchFilter ) );
$('#reset').on( 'click', function() {
$quicksearch.val('');
searchFilter()
});
// store filter for each group
$('#filters').on( 'click', '.button', function() {
var $this = $(this);
// get group key
var $buttonGroup = $this.parents('.button-group');
var filterGroup = $buttonGroup.attr('data-filter-group');
// set filter for group
filters[ filterGroup ] = $this.attr('data-filter');
// combine filters
var filterValue = '';
for ( var prop in filters ) {
filterValue += filters[ prop ];
}
// set filter for Isotope
$container.isotope({ filter: filterValue });
});
// debounce so filtering doesn't happen every millisecond
function debounce( fn, threshold ) {
var timeout;
return function debounced() {
if ( timeout ) {
clearTimeout( timeout );
}
function delayed() {
fn();
timeout = null;
}
setTimeout( delayed, threshold || 100 );
}
}
How do I solve the problem?
Note: I am using jQuery 2.1.1.
In you example $('#filters').on('click', '.button', function () stoping the search function and you reset buton placed inside #filters div so when you click it search engine is stoped too.
I have not the best solution, but it solve some problems:
Idea in using function to call engine back:
var iso = function() {
//engine here
}
and
$(function () {
iso();
$('.iso').click(function(){
setTimeout(iso, 500);
});
});
without setTimeout it can't work.
But it don't solve the main problem
look at FIDDLE and you'll understand what I mean
Or you just can place reset and Show All buttons outside #filters div
I faced the same problem implementing Filters + Search functionality.
I solved this problem passing the filter function to the Isotope call ($container.isotope();) in the search function (function searchFilter(){...}) instead of when initializing the Isotope instance.
So, in your code it should be like this:
// No filter specified when initializing the Isotope instance
$container.isotope({
itemSelector : '.element',
masonry : {
columnWidth : 120
},
getSortData : {
name : function ( $elem ) {
return $elem.find('.name').text();
}
}
});
// Instead, the filter is specified here
function searchFilter() {
qsRegex = new RegExp( $quicksearch.val(), 'gi' );
$container.isotope({
filter: function() {
return qsRegex ? $(this).text().match( qsRegex ) : true;
}
});
}
just need a little help here. My problem is, how can I count the seconds when i hover a specific element. Like for example when I hover a button, how can i count the seconds did i stayed in that button after I mouseout?
An alternate solution using setInterval. DEMO HERE
var counter = 0;
var myInterval =null;
$(document).ready(function(){
$("div").hover(function(e){
counter = 0;
myInterval = setInterval(function () {
++counter;
}, 1000);
},function(e){
clearInterval(myInterval);
alert(counter);
});
});
A simple example
var timer;
// Bind the mouseover and mouseleave events
$('button').on({
mouseover: function() {
// set the variable to the current time
timer = Date.now();
},
mouseleave: function() {
// get the difference
timer = Date.now() - timer;
console.log( parseFloat(timer/1000) + " seconds");
timer = null;
}
});
Check Fiddle
How about this quick plugin I just knocked out, which will work on multiple elements, and without using any global variables:
(function($) {
$.fn.hoverTimer = function() {
return this.on({
'mouseenter.timer': function(ev) {
$(this).data('enter', ev.timeStamp);
},
'mouseleave.timer': function(ev) {
var enter = $(this).data('enter');
if (enter) {
console.log(this, ev.timeStamp - enter);
}
}
});
};
})(jQuery);
Actually disabling the functionality is left as an exercise for the reader ;-)
Demo at http://jsfiddle.net/alnitak/r9XkX/
IMHO, anything using a timer for this is a poor implementation. It's perfectly trivial to record the time without needing to use an (inaccurate) timer event to "count" seconds. Heck, the event object even has the current time in it, as used above.
This is exam:
var begin = 0;
var end = 0;
$('#btn').hover(function () {
begin = new Date().getTime();
});
$('#btn').leave(function () {
end = new Date().getTime();
sec = (end - begin) / 1000;
alert(sec);
});
One way to go about it would be the event.timeStamp method :
var initial_hover, exit_hover;
$('#ele').hover(
function(event){
initial_hover = event.timeStamp
console.log(initial_hover);
},
function(event){
exit_hover = event.timeStamp
$(this).html(exit_hover - initial_hover);
console.log(exit_hover);
}
);
jsfiddle
You've tagged the question with JQuery, so here's a jQuery solution.
$(element).on('mouseover', function(e){
$(e.target).data('hover-start', new Date().getTime());
});
$(element).on('mouseout', function(e){
// count the difference
var difference = new Date().getTime() - $(e.target).data('hover-start');
// clean up the data
$(e.target).data('hover-start', undefined);
console.log('Mouse was over for', difference/1000, 'seconds');
});
use setInterval and store value in variable. call the function on mouserover.
function mouseover(){
var start = 0;
setInterval(function(){
start++;
var count = start;
}, 1000);
}