I'm using Leaflet to insert a map into Qualtrics. For one of my markers, I have it set up so that (1) a popup appears with a mouse hover and (2) clicking on the popup continues on to the next page in the experiment:
marker1.on('mouseover', function (e) {
this.openPopup();
this.getPopup()._contentNode.onclick = function () {
document.querySelector("#NextButton").click();
Qualtrics.SurveyEngine.setEmbeddedData("home", "one");
};
});
Is it also possible to use embedded data to also record when the mouse hover occurs with a time stamp? If so, how?
Use a function to get a new Date(). When no parameters are provided, the newly-created Date object represents the current date and time as of the time of instantiation. Then you can get the parameters you wish using the getDay(), getMonth(), getHours(), getMinutes(), etc... return your timestamp and then you can call on the function within your event listener mouseover.
Not sure how you wish to save it further however...
const getTimeStamp = () => {
let d = new Date();
let hours = d.getHours();
let meridian;
if (hours > 12) {
hours = hours - 12;
meridian = 'PM';
}else{
meridian = 'AM';
}
let time = `${hours}:${d.getMinutes()}:${d.getSeconds()} ${meridian}`;
let day = d.getDate();
let month = d.getMonth() + 1; // Since getMonth() returns month from 0-11 not 1-12
let year = d.getFullYear();
let timeStamp = `${month}/${day}/${year} - ${time}`;
return timeStamp;
}
let marker1 = document.getElementById('marker1')
marker1.addEventListener('mouseover', function(e) {
console.log(getTimeStamp())
// this.openPopup();
// this.getPopup()._contentNode.onclick = function() {
// document.querySelector("#NextButton").click();
// Qualtrics.SurveyEngine.setEmbeddedData("home", "one");
// };
});
<buttton id="marker1">Marker</div>
Related
//<![CDATA[
var displayCurrentTime = new function() {
// Get values...
var sysHour = getHours(); // Get Hours
var curHour = 0; // Initialize current hour (12 hr format)
var morningEvening = "AM"; // Initialize AM/PM notation
if (sysHour < 13) { // If it's in the morning, set time as is.
curHour = sysHour;
morningEvening = "AM"
} else {
curHour = sysHour - 12; // If it's in the evening, subtract 12 from the value and use "PM"
morningEvening = "PM"
}
var curMins: getMinutes; // Get current minutes...
// Capture the ID of the notification bar div, and compose a string from the above values.
var notificationBar = document.getElementById("notificationBar");
var dateTimeString = curHour + ":" + curMins + " " + morningEvening;
// All that code above files into this fun stuff.
notificationBar.innerHTML = dateTimeString;
}
window.setInterval(function() {
displayCurrentTime();
}, 1000);
//]]>
I've been reading up some information and I wanted to create a simple script that grabs the hour and minute, does some calculations to determine if it's AM or PM, creates a string variable from those results, and then slips it inside of a specific DIV element. It does this every second.
Most of the code I've written seems to make sense based on what I've read. In the beginning I've tried using function displayCurrentTime() {} as well as what you see below (var displayCurrentTime = new function() {}) and neither seem to work. I cannot get my text to display in the page. Note: the ID of the div is notificationBar, just as it is here.
Is there anything in this code that makes no sense, or does this actually warrant posting the full HTML?
You don't need new in front of function that you newly define, you don't instantiate class.
You have few syntax errors, like var curMins : ... instead of var curMins = ....
Also, you cannot use getHours() and getMinutes() methods, outside of Date object:
var displayCurrentTime = function() {
// Get values...
var d = new Date();
var sysHour = d.getHours(); // Get Hours
var curHour = 0; // Initialize current hour (12 hr format)
var morningEvening = "AM"; // Initialize AM/PM notation
if (sysHour < 13) { // If it's in the morning, set time as is.
curHour = sysHour;
morningEvening = "AM"
} else {
curHour = sysHour - 12; // If it's in the evening, subtract 12 from the value and use "PM"
morningEvening = "PM"
}
var curMins = d.getMinutes(); // Get current minutes...
var curSecs = d.getSeconds(); //optionally get seconds too
// Capture the ID of the notification bar div, and compose a string from the above values.
var notificationBar = document.getElementById("notificationBar");
var dateTimeString = curHour + ":" + curMins + ":" + curSecs + " " + morningEvening;
// All that code above files into this fun stuff.
notificationBar.innerHTML = dateTimeString;
}
window.setInterval(function(){ displayCurrentTime(); }, 1000);
<div id='notificationBar'>
Time Here
</div>
See about Date object:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
About functions and anonymous function expression:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions#The_function_expression_(function_expression)
Also:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Howto
There are a few syntax errors in your function, I'll get to them one by one:
You shouldn't use new when declaring a function. Just drop it =) var displayCurrentTime = function() {
You are trying to assign a value to a variable using json syntax : in var minutes: getMinutes. You also forgot to execute the function, so try var minutes = getMinutes();
In (2) I assume you already declared the methods getHours and getMinutes, but if not, you can call them directly from a new Date object:
var date = new Date();
var sysHours = date.getHours();
var minutes = date.getMinutes();
//...
That should do it!
Extra: you can skip adding the displayCurrentTime to another function inside the setInterval function: window.setInterval(displayCurrentTime, 1000);
var displayCurrentTime = function() {
var date = new Date(); // Get current date object
var sysHour = date.getHours(); // Get Hours
var curHour = 0; // Initialize current hour (12 hr format)
var morningEvening; // No need to initialize
if (sysHour < 13) { // If it's in the morning, set time as is.
curHour = sysHour;
morningEvening = "AM"
} else {
curHour = sysHour - 12; // If it's in the evening, subtract 12 from the value and use "PM"
morningEvening = "PM"
}
var curMins = date.getMinutes(); // Get Minutes
// Capture the ID of the notification bar div, and compose a string from the above values.
var notificationBar = document.getElementById("notificationBar");
var dateTimeString = curHour + ":" + curMins + " " + morningEvening;
// All that code above files into this fun stuff.
notificationBar.innerHTML = dateTimeString;
}
window.setInterval(displayCurrentTime, 1000);
<div id='notificationBar'></div>
Currently i'm facing the following problem. In my JavaScript code, i have a function, which should calculate the weeks from now, to a given timestamp. The problem is, that the the first value has the same Value as another variable with another name. The code:
let myAppointment = event.data.toTime;
console.log(myAppointment);
let currentDate = new Date(Date.now());
let currentTime = (convertStringDateToDate(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), 0,0,0,0)).getTime();
let appointmentStartDate = new Date(myAppointment.getStart());
console.log(appointmentStartDate);
console.log(currentDate);
let appointmentStartTime = (convertStringDateToDate(appointmentStartDate.getFullYear(), appointmentStartDate.getMonth(), appointmentStartDate.getDate(),0,0,0,0)).getTime();
console.log('AppointmentStartTime : ' + appointmentStartTime);
console.log('CurrentTime: ' + currentTime);
let timeskip = appointmentStartTime - currentTime;
console.log(timeskip + ' timeskip / 604800000 = ' + (timeskip / 604800000));
skips = timeskip / 604800000;
await displayCalendar(document.getElementById('wrapper'));
console.log(skips);
if(skips < 0){
skips = Math.floor(skips);
if(Math.abs(skips) != 1){
navigateBackward(skips);
}
}else{
skips = Math.floor(skips);
if(Math.abs(skips) != 1){
navigateForward(skips);
}
}
cleanTable();
displayAppointments();
});
//i think this function may be interesting too, but the error can't occur from here
function
convertStringDateToDate(year,month,day,hours,minutes,seconds,milliseconds){
let date = new Date();
date.setFullYear(year);
date.setMonth(month);
date.setDate(day);
date.setHours(hours);
date.setMinutes(minutes);
date.setSeconds(seconds);
date.setMilliseconds(milliseconds);
return date;
}
The function from let myAppointment = ... Leads to the following console output
The problem lies here:
let appointmentStartTime = (convertStringDateToDate(appointmentStartDate.getFullYear(), appointmentStartDate.getMonth(), appointmentStartDate.getDate(),0,0,0,0)).getTime();
You set the hours, minutes, seconds all to zero - effectively turning your start date to the same value as today's date.
Note that in your particular example, currentDate and appointmentStartDate share the same year, month, and date. When you call let currentTime = (convertStringDateToDate(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), 0,0,0,0)).getTime();
, you should replace 0,0,0,0 with correct values for both currentTime and appointStartTime.
To make your coding style consistent, you can use date.getHours(), date.getMinutes(), date.getSeconds(), and date.getMilliseconds() to replace those four zeroes.
Also, if you want to shorten your code, you can get rid of convertStringDateToDate() and merely call getTime() on currentDate and appointStartDate.
let currentDate = new Date();
let currentTime = (convertStringDateToDate(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), currentDate.getHours(),currentDate.getMinutes(),currentDate.getSeconds(),currentDate.getMilliseconds())).getTime();
console.log(currentTime); // 1537309553647
console.log(currentDate.getTime()); // 1537309553647
I've run into a problem whilst building a clock using Vanilla Javascript.
I'm getting the current time fine but I would like the user to be able to set their own time. The time the user wants is grabbed from three input fields and passed in as optional paramters(updateH,updateM,updateS) to the below function:
function updateTime(updateH,updateM,updateS){
updateH = updateH || false; updateM = updateM || false; updateS = updateS || false;
today = new Date();
if (updateH != false || updateM != false || updateS != false) {
today.setHours(updateH);
today.setMinutes(updateM);
today.setSeconds(updateS);
}
h = addLeadingZeroes(today.getHours()); //Today's time (hours)
m = addLeadingZeroes(today.getMinutes()); //Today's time (minutes)
s = addLeadingZeroes(today.getSeconds()); //Today's time (seconds)
day = getDay().toUpperCase(); //Today's date (day)
date = today.getaDmante(); //Today's date (date)
month = getMonth().toUpperCase(); //Today's date (month)
time24H = h + ":" + m + ":" + s;
drawWatch();
setTimeout(updateTime, 1000);
}
updateTime();
This function is ran every second (1000ms), therefore the clock resets itself to the current time after one second, making the users choice time dissapear.
Is there anyway to update the time to the user passed in time and then continue the clock ticking using the new time? E.G:
The clock reads '12:00:00', the user then enters the time '13:30:00', now the clock continues ticking from '13:30:01....13:30:02....13:30:03...ETC'.
Many thanks for your help!
When the user sets the their time, calculate the difference between their time and the current time, store this value. Then each time you want to redraw the watch just get the new current time, subtract that stored difference and redraw the watch.
Personally I would create a new prototype called "Watch" and just do all the things you want within this object.
/* Create a "Watch" prototype */
function Watch(hours, minutes, seconds, drawInterval){
var t = this;
this.offset = 0;
this.drawInterval = drawInterval || 1000;
this.setTime = function(hours, minutes, seconds){
var now = new Date().getTime();
var theirTime = new Date();
if(hours) theirTime.setHours(hours);
if(minutes) theirTime.setMinutes(minutes);
if(seconds) theirTime.setSeconds(seconds);
this.offset = now - theirTime.getTime();
};
this.getTime = function(){
var d = new Date( new Date() - this.offset );
return d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
};
this.draw = function(elementID){
function draw(){
document.getElementById(elementID).innerHTML = t.getTime();
setTimeout(draw, t.drawInterval);
};
draw();
};
this.setTime(hours, minutes, seconds); // Initialize
}
/* Create an instance of the "Watch" prototype */
var W = new Watch();
/* Draw the watch to the DOM */
W.draw("watch");
/* Set the Users Time */
W.setTime(12,45,30); // 12:45:30
<div id='watch'></div>
I have 2 times for example: 10:00 and 1:00 now i want to check if current time... is between these 2 times in javascript.
The problem is that the closing time in this case is a next day so its before the openingstime. How can i do this the proper way for some reason i can not get around this.
i hav efound that this could solve it:
var start = new Date(2012,6,20,13).getTime();
var now = new Date().getTime();
var end = new Date(2012,6,21,2).getTime();
if( (start < now ) && (now < end )) {
console.log("opened");
}
else {
console.log("closed");
}
but how can i do it with 2 string formats like 10:00 and 2:00 because i do not see a option to put a time alone
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
You could use a simple function like this to convert your time to a number of minutes since 0:00:
function getMinutes(str) {
var time = str.split(':');
return time[0]*60+time[1]*1;
}
And a similar function to get the current time into the same form in order to compare:
function getMinutesNow() {
var timeNow = new Date();
return timeNow.getHours()*60+timeNow.getMinutes();
}
Then convert both opening and closing time and, if it happens that closing time is before opening time, add 24 hours to it.
var now = getMinutesNow();
var start = getMinutes('10:00');
var end = getMinutes('2:00');
if (start > end) end += getMinutes('24:00');
if ((now > start) && (now < end)) { // your code here
This is the solution I've gotten to after a bit of fiddling. At the current time of 3:24 am, it outputs the correct information. changing the now array to be [13,00] also gave the correct result of 'closed' Give it a test run through to make sure it works correctly.
Edit
jQuery included solely because I am brain dead.
Edit#2
I noticed now (9pm my time) that my conversion wasn't working, it was saying 'closed', when it shouldn't have. So far, this works for any and all numbers I've put in it to test.
var start_time = [20,00]
var end_time = [12,00]
//We've got the two start times as an array of hours/minutes values.
var dateObj = new Date(); //I just feel dirty making multiple calls to new Date().etc
var now = [dateObj.getHours(),dateObj.getMinutes()]; //Gets the current Hours/Minutes
if(end_time[0] < start_time[0] && now[0] < start_time[0]){
start_time[0] -= 24; //This is something I came up with because I do a lot of math.
}else if(start_time[0] > end_time[0]){
end_time[0]+=24;
}
var el=$('#result');
var start_string = to_hms_string(start_time); //the start string converted to a string format. Made comparisons easier.
var end_string = to_hms_string(end_time); //See Above
var now_string = to_hms_string(now); //Above
console.log(start_string, now_string, end_string);
var status = (start_string < now_string && now_string < end_string) ? "Open" : "Closed";
el.html(status);
//Function to_hms_string stands for "hour-minute-second" string. First name that came up.
function to_hms_string(timearr){
var minutes = 60+timearr[1];
var hours = "";
if(Math.abs(timearr[0]) < 10){
hours = "0";
}
hours = (timearr[0]<0) ? "-"+hours+Math.abs(timearr[0]) : hours+timearr[0];
return hours+":"+minutes;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">
PlaceHolder
</div>
You can do this, get current time. Then define you start time and end time based on the current time getting the year, month, date for tomorrow's date add 1 to the start's date see code below. Then you can compare the time the same fi condition you have. Good luck
var now = new Date();
var start = new Date(now.getFullYear(),now.getMonth(),now.getDate(),7).getTime();
var end = new Date(now.getFullYear(),now.getMonth(),now.getDate() + 1,2).getTime();
now = now.getTime();
if( now >= start && now < end) {
console.log("opened");
}
else {
console.log("closed");
}
***EDIT**
You can convert the current time to millis after you get the year, month and date. Then use your current if condition.
Jhecht This thing right here:
if(end_time[0] < start_time[0] && now[0] < start_time[0]){
start_time[0] -= 24;
}else if(start_time[0] > end_time[0]){
end_time[0]+=24;
}
it's brilliant. It works and this is the correct answer. Great job!
I have a table to which i dynamically add rows. The number of days is equal to the date difference of the dates inserted by user. On the dynamic rows i want to add three fields. The first two are date and day filed. For that I need to know the next date and the corresponding day. For example user enters 10-2-2012. I need to insert The next dates like 17-2-2012,18-2-2012... and corresponding days like Wednesday, Thursday..etc
I have used the following function to get next date
function getTomorrow(d,offset)
{
if (!offset)
{
offset = 1
}
return new Date(new Date().setDate(d.getDate() + offset));
}
But it shows error 16-2-2012 has no getDate() function. Am not able to find next date and the corresponding day. Is there any way to get it?
You have to convert the string d into a Date object:
function getTomorrow(d,offset){
if (!offset){
offset = 1;
}
if(typeof(d) === "string"){
var t = d.split("-"); /* splits dd-mm-year */
d = new Date(t[2],t[1] - 1, t[0]);
// d = new Date(t[2],t[1] - 1, t[0] + 2000); /* for dd-mm-yy */
}
return new Date(d.setDate(d.getDate() + offset));
}
document.write(getTomorrow('16-02-2012',20) + ' test');
var k = getTomorrow('16-02-2012',1);
var myTime = k.getDate()+'-'+(k.getMonth()+1)+'-'+k.getFullYear();
alert(myTime);
JSFiddle Demo. See also http://www.w3schools.com/jsref/jsref_obj_date.asp.
var d=new Date();
d.setTime((d.getTime() + 86400 * 1000*1));
document.write(d);
document.write(d.getDay()+"-"+parseInt(d.getMonth()+1)+"-"+d.getFullYear());
if you need to know the date of day after tommorow , just change 1000*1 to 1000*2.
i giving a example
var year = 2010, month = 9, day = 14;
// The value of `meses`
var offset = 1; // Tomorow
var future_date = new Date(year, month , day+offset);
console.log(future_date);