How to get Time with Cookies javascript When I close the tab or Page?
i'm try use window.onunload but time can not be stored in cookies..
in this code i'm push my cookies to be array
setCookie("time",time,1)
window.onunload =function (){
var set = getCookie('time');
var arr = [];
var push = arr.push(set);
console.log (arr);
return arr;
}
In JavaScript, there is a class called "Date" that let's you get the current time.
var d = new Date(); creates a new Date object and assigns it to the variable d
Now, you have the date and time - you can do whatever you like.
For example: document.getElementById('foo').innerHTML = d.toString() finds the element with the ID of "foo" and sets it's contents to the date and time.
Keep in mind that this date and time display will not constantly update itself. You will have to do that with some timed recursion.
There are many more things you can do with dates. Remember, Google is your friend - look up some things about the Date object.
Related
Important: Even though this could probably be done with php (I'm using WooCommerce on Wordpress), I want this script to run only on my browser. That's why I want to do it in Javascript. Hence, I'm using Custom Javascript for Websites to load my script from my browser.
What my script should do: Check if the data of a specific element has been changed.
Logic: Step 1) Get and locally remember specific string (order number) of a specific class. Step 2) Refresh the page. Step 3) Again get the specific string (order number) of a specific class. Step 4) If strings do not match, run a function (play an audio).
Problem: After page reloads, the script starts to run again from the beginning. Hence, it results in overriding the stored string. As a result, stored and newly fetched string are always equal.
Question: How do I make the script to run the 3rd step only after refresh so that the stored data doesn't override itself?
Current code:
var OrderIdOld = document.getElementsByClassName("row-title"); // Select every single element with ClassName "row-title"
var x = (OrderIdOld[0].innerText); // Get the string of the first element of the class "row-title"
var compareOld = x.slice(-1); // Get the last element of the string (since it will be a number, we can change the string into a number easily later)
localStorage.setItem("compareOld", compareOld); // Store this element in local storage, so that it can be used after page reloads.
setInterval ("window.location.reload()", 30000); // Reload page every 30 secs.
var remembered = localStorage.getItem("compareOld"); // Assign stored element to a new var.
var n = compareOld.valueOf(); // Turn stored element into a number (for easy comparison later).
var OrderIdNew = document.getElementsByClassName("row-title"); // Select every single element with ClassName "row-title"
var y = (OrderIdNew[0].innerText); // Get the string of the first element of the class "row-title"
var compareNew = y.slice(-1); // Get the last element of the string (since it will be a number, we can change the string into a number easily later)
var m = compareNew.valueOf(); // Turn fetched element into a number (for easy comparison later).
function beep() {
var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxEjzFUgfHoSQ9Qq7KNwqHwuB13MA4a1q/DmBrHgPcmjiGoh//EwC5nGPEmS4RcfkVKOhJf+WOgoxJclFz3kgn//dBA+ya1GhurNn8zb//9NNutNuhz31f////9vt///z+IdAEAAAK4LQIAKobHItEIYCGAExBwe8jcToF9zIKrEdDYIuP2MgOWFSE34wYiR5iqQPj0JIeoVdlG4VD4XA67mAcNa1fhzA1jwHuTRxDUQ//iYBczjHiTJcIuPyKlHQkv/LHQUYkuSi57yQT//uggfZNajQ3Vmz+Zt//+mm3Wm3Q576v////+32///5/EOgAAADVghQAAAAA//uQZAUAB1WI0PZugAAAAAoQwAAAEk3nRd2qAAAAACiDgAAAAAAABCqEEQRLCgwpBGMlJkIz8jKhGvj4k6jzRnqasNKIeoh5gI7BJaC1A1AoNBjJgbyApVS4IDlZgDU5WUAxEKDNmmALHzZp0Fkz1FMTmGFl1FMEyodIavcCAUHDWrKAIA4aa2oCgILEBupZgHvAhEBcZ6joQBxS76AgccrFlczBvKLC0QI2cBoCFvfTDAo7eoOQInqDPBtvrDEZBNYN5xwNwxQRfw8ZQ5wQVLvO8OYU+mHvFLlDh05Mdg7BT6YrRPpCBznMB2r//xKJjyyOh+cImr2/4doscwD6neZjuZR4AgAABYAAAABy1xcdQtxYBYYZdifkUDgzzXaXn98Z0oi9ILU5mBjFANmRwlVJ3/6jYDAmxaiDG3/6xjQQCCKkRb/6kg/wW+kSJ5//rLobkLSiKmqP/0ikJuDaSaSf/6JiLYLE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BUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU=");
snd.play();
} // Function that will play the sound.
if (n!=m) {
beep();
} // Run function if two numbers are not equal.
Additional: I have gathered the parts of the code from various Questions on stackoverflow. Meaning, I have been searching about this topic for the past week. This is my first questions ever. Hopefully I formatted the question so that it easy to understand.
EDIT: The issue has been solved. I used the idea of only running the first step of function on the first load of page. This post helped me to get functionality working https://stackoverflow.com/a/22334768/7929506
The working code looks like this:
function beep() {
window.open('https://www.youtube.com/watch?v=EQ3zPIj2O5k','_blank');
}
if (sessionStorage.getItem("visit") == null) {
var OrderIdOld = document.getElementsByClassName("row-title")[0].innerText.slice(-1).valueOf();
sessionStorage.setItem("OrderIdOld", OrderIdOld);
sessionStorage.setItem("visit", new Date());
setTimeout("window.location.reload()", 10000);
}
else {
var OrderIdNew = document.getElementsByClassName("row-title")[0].innerText.slice(-1).valueOf();
var x = sessionStorage.getItem("OrderIdOld");
if (x==OrderIdNew) {
setTimeout("window.location.reload()", 10000);
}
else {
beep();
var x = sessionStorage.getItem("OrderIdOld");
sessionStorage.removeItem("OrderIdOld");
sessionStorage.removeItem("visit");
setTimeout("window.location.reload()", 10000);
}
}
When you refresh the page first time, you can simply append a flag variable to URL to identify weather its a refresh or a first time load. Based on that, you can pass a localized variable to script and if that is set then you need to refresh else not.
What are the objects in JavaScript that we use for running time on webpage?
I tried using getElementId() method and could not do it.
If you want to get the current date and time,
var now = new Date()
var deadline = new Date(now.getFullYear, now.getMonth, now.getDate, now.getHours, now.getMinutes + 15);
Then you can fill an element with the deadline variable.
See here
https://blog.smalldo.gs/2013/12/create-simple-countdown/
I want to receive an array of moment objects, based on start / and date.
I wrote the following code in which the first start date is 27/12/2014:
_calculateDateInterval: function(date_start, date_end){
var current = date_start.startOf("day");
var arr_dates = [];
var i = 1;
while(date_end.startOf("day").diff(current, "days") > 0){
var copy_current = $.extend({}, current); //Clone the object without reference
console.log(copy_current);
arr_dates.push(copy_current);
current.add(1, "days");
//Break the loop for testing purposes
i++;
if(i == 2){
return false;
};
};
return arr_dates;
},
There is a problem though. Even when checking only on the first loop, the console gives me the following log:
This is confusing; when opening the dropdown, _d shows another day than when it is collapsed.
In order to store the right moment object, I need to remove the reference to the original (current) Moment object of which the day is increased on each loop. (In this case I need 27/12/2014, not the value including the day increase).
Any (better) suggestions?
Found it already in the docs:
All moments are mutable. If you want a clone of a moment, you can do
so explicitly or implicitly.
Calling moment() on a moment will clone it.
Hi this is making me nuts. I am not a developer. Trying to get this to work.
User puts in a date (hire date) into form using Date object (calendar)
Next field should take that date and subtract todays date to get the length of employment.
But I get undefined in the field AND my original hire date disappears.
Here is what I have, help please, much appreciation!
//grab date of hire
try{document.getElementById("dData_DOH").onchange = custom_calculateDate;}catch(e){}
//not sure if necessary - field that the difference should go to
try{document.getElementById("dData_LengthEmp").onblur = insertDate;}catch(e){}
//Function to grab input hire date
//Create variable for now
//Create variable for difference
function custom_calculateDate(){
var hireDate = document.getElementById("dData_DOH").value = "";
var timeNow= new Date();
var diff = Math.abs(timeNow - hireDate);
document.getElementById("dData_DOH").setAttribute('value', custom_calculateDate());
}
//Function to get the difference into the LengthEmp field
function insertDate() {
document.getElementById("dData_LengthEmp").setAttribute("", custom_calculateDate());
}
I know this is completely wrong, as I said I am not a developer or programmer, I cannot figure out how to get this information into this field and get my original field to still show.
Thank you for reading this!
Use value instead of setAttribute
document.getElementById("dData_DOH").value = custom_calculateDate();
Wow wow wow.
I'll try to rewrite your code by giving you explainations about why:
// Firstly, the onchange event doesn't work on IE for text inputs, prefer onblur
document.getElementById('dData_DOH').onblur = function(e) {
// Now let's get some variables
var hireDate = this.value, // "this" refers to the element that triggered the event
now = new Date(),
// You were on the right track for the difference, almost!
diff = Math.abs(new Date(now.getTime() - hireDate.getTime()))
// Finally, just don't change the original field, but the one you wanted to modify
document.getElementById('dData_LengthEmp').value = diff.toTimeString() // Get the time as a readable format
}
I haven't tested the solution, but it should get you on the track.
Btw, don't use try/catch.
I am writing a timer web app,which records start time and stop time.It uses javascript,jquery1.4.2 for the front end and python for backend code.When a start button is clicked ,start time is saved in a javascript variable.when the button is clicked again, stop time is saved in another variable.These values are passed as hidden parameters to the python code which gets the start,stop values from django's request parameter.
I expect the start/stop parameters values to be in the following format
"07:16:03 PM"
so that it can be parsed using '%I:%M:%S %p'format string.
I am getting this correctly in mozilla firefox.But when I use chrome,I only get
"19:16:03"
This causes value error when I try to parse it with the above format string.
import time
...
def process_input(request,...):
start_time=request.POST[u'timerstarted']
...
fmtstr='%I:%M:%S %p'
start_time_list = list(time.strptime(start_time,fmtstr)[3:6])
I tried putting alert('start time set as'+start_time) in javascript to find what values are set in the page's hiddenfields
With firefox ,I got
start time set as08:03:09 PM
stop time set as08:03:43 PM
but with chrome
start time set as20:04:21
stop time set as20:04:32
My knowledge of javascript,jquery is minimal.Why is the script behaving differently in these two browsers? Below is the javascript snippet
$(document).ready(function(){
var changeBtnStatus=function(){
var timebtnvalue=$('#timebtn').attr("value");
if (timebtnvalue =="start"){
...
var start_date=new Date();
var str_time=start_date.toLocaleTimeString();
var timerstartedfield =$('#timerstarted');
timerstartedfield.attr("value",str_time);
alert('start time set as'+str_time);
}
else if (timebtnvalue=="stop"){
...
var stop_date=new Date();
var stp_time=stop_date.toLocaleTimeString();
var timerstoppedfield =$('#timerstopped');
timerstoppedfield.attr("value",stp_time);
alert('stop time set as'+stp_time);
}
};
var timerBtnClicked=function(){
...
changeBtnStatus();
};
$('#timebtn').click(timerBtnClicked);
...
}
);
You don't want the string of the time in locale, using the toString method you can provide your own format, or use toUTCString().
toLocaleTimeString is especially meant to display the time as the user is used to, you want it in a set format.
So instead of start_date.toLocaleTimeString(), you want to use start_date.toUTCString().
Why format the time in JavaScript and parse in Python, and even submit yourself to the confusion of different locales?
Try using Date.getTime insteam:
start_time = (new Date).getTime();
stop_time = (new Date).getTime();
This gets you the time in milliseconds since the epoch, which should always be stable.