I am trying to use LocalStorage to save data. I want to use this data to reinitialise a counter after the user refreshes. An example of my code can be found in the following JSFiddle.
var hj= document.getElementById("jam");
var mm= document.getElementById("menit");
var ds= document.getElementById("detik");
var startDateTime = new Date();
var startStamp = startDateTime.getTime();
console.log(startDateTime);
console.log(startStamp);
var newDate = new Date();
var newStamp = newDate.getTime();
// console.log(newStamp);
var timer;
function pad(val) {
return val > 9 ? val : "0" + val;
}
function updateClock() {
newDate = new Date();
newStamp = newDate.getTime();
var diff = Math.round((newStamp-startStamp)/1000);
var d = Math.floor(diff/(24*60*60));
diff = diff-(d*24*60*60);
var h = Math.floor(diff/(60*60));
diff = diff-(h*60*60);
var m = Math.floor(diff/(60));
diff = diff-(m*60);
var s = diff;
// document.getElementById("time-elapsed").innerHTML = d+" day(s), "+h+" hour(s), "+m+" minute(s), "+s+" second(s) working";
document.getElementById("jam").innerHTML=pad(h);
document.getElementById("menit").innerHTML=pad(m);
document.getElementById("detik").innerHTML=pad(s);
}
var time=setInterval(updateClock, 1000);
https://jsfiddle.net/o5s4y2L7/
You can use a Cookie for this.
var hj= document.getElementById("jam");
var mm= document.getElementById("menit");
var ds= document.getElementById("detik");
var startDateTime = new Date();
var cookie_time = getCookie("timer_start");
var startStamp = cookie_time?cookie_time:startDateTime.getTime();
setCookie("timer_start", startStamp, 1);
var newDate = new Date();
var newStamp = newDate.getTime();
var timer;
function pad(val) {
return val > 9 ? val : "0" + val;
}
function updateClock() {
newDate = new Date();
newStamp = newDate.getTime();
var diff = Math.round((newStamp-startStamp)/1000);
var d = Math.floor(diff/(24*60*60));
diff = diff-(d*24*60*60);
var h = Math.floor(diff/(60*60));
diff = diff-(h*60*60);
var m = Math.floor(diff/(60));
diff = diff-(m*60);
var s = diff;
document.getElementById("jam").innerHTML=pad(h);
document.getElementById("menit").innerHTML=pad(m);
document.getElementById("detik").innerHTML=pad(s);
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length,c.length);
}
}
return "";
}
var time=setInterval(updateClock, 1000);
Related
I am new to JS so any help would be appreciated.
I have created an XML request upon the page loading a video to check for cookies, and then replace a div element "tmx" with an external HTML file from my website. However the page keeps on reloading after fetching the XML request after injecting it to "#tmx".
Another thing that I noticed is when I press accept tnc button on my document without the checkbox being ticked, the whole page is being completely reloaded.
I think it might be the return value that might be wrong.
function setCookie(cname, cvalue, exdays) {
if(document.getElementById('agree').checked){
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
function checkCookieOnLoad() {
if(getCookie("clicklink") === "yes") {
var elem = document.getElementById("tmx");
elem.parentNode.removeChild(elem);
// var elem2 = document.getElementById("ooo");
// elem2.parentNode.removeChild(elem2);
var video = document.createElement('video');
video.type = "video/mp4";
video.src = ".//vid1.mp4";
video.autoplay = true;
video.muted = true;
video.id = "vdd1"
document.body.appendChild(video);
video.addEventListener("timeupdate", function(){
// current time is given in seconds
if(this.currentTime >= 4.8) {
// pause the playback
this.pause();
this.remove();
location.replace("https://www.test.com/index.html");
}
});
return true;
} else {
const xhr = new XMLHttpRequest();
const contianer = document.getElementById('tmx');
xhr.onload = function() {
if (this.status ===200){
contianer.innerHTML = xhr.responseText;
}
}
xhr.open('get', 'tnc.html');
xhr.send();
}
}
setTimeout(function() {
function setCookie(cname, cvalue, exdays) {
if (document.getElementById('agree').checked) {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
function checkCookieOnLoad() {
if (getCookie("clicklink") === "yes") {
var elem = document.getElementById("tmx");
elem.parentNode.removeChild(elem);
// var elem2 = document.getElementById("ooo");
// elem2.parentNode.removeChild(elem2);
var video = document.createElement('video');
video.type = "video/mp4";
video.src = ".//vid1.mp4";
video.autoplay = true;
video.muted = true;
video.id = "vdd1"
document.body.appendChild(video);
video.addEventListener("timeupdate", function() {
// current time is given in seconds
if (this.currentTime >= 4.8) {
// pause the playback
this.pause();
this.remove();
location.replace("https://www.test.com/index.html");
}
});
return true;
} else {
const xhr = new XMLHttpRequest();
const contianer = document.getElementById('tmx');
xhr.onload = function() {
if (this.status === 200) {
contianer.innerHTML = xhr.responseText;
}
}
xhr.open('get', 'tnc.html');
xhr.send();
}
}
}, 5000);
/*This code will run after 5 seconds after the loading of HTML CSS and your JS files. Try it. Hope it helps you!!*/
I have a PHP function which calculates the time difference (hr/min/sec) of two values:
$mf_start_time = '10:00:00';
$mf_end_time = '11:00:00';
$st_start_time = '10:00:00';
$st_end_time = '12:00:00';
$sn_start_time = '10:00:00';
$sn_end_time = '13:00:00';
$ph_start_time = '10:00:00';
$ph_end_time = '14:00:00';
function time_interval($start,$end) {
$s = strtotime($start);
$e = strtotime($end);
if ($s < $e)
{
$a = $e - $s;
}
else
{
$e = strtotime('+1 day',$e);
$a = $e - $s;
}
$h = floor($a/3600);
$m = floor(($a%3600)/60);
$s = $a%60;
return trim(($h?$h.' hour ':'').($m?$m.' minute ':'').($s?$s.' second ':''));
}
$mf_duration = time_interval($mf_start_time,$mf_end_time);
$st_duration = time_interval($st_start_time,$st_end_time);
$sn_duration = time_interval($sn_start_time,$sn_end_time);
$ph_duration = time_interval($ph_start_time,$ph_end_time);
echo $mf_duration;
echo $st_duration;
echo $sn_duration;
echo $ph_duration;
My output for this is:
1 hour
2 hour
3 hour
4 hour
Now I am trying to translate this into Javascript, my problem is that I need to get strtotime() to work the same.
Here is what I tried in Javascript:
var mf_start_time = '10:00:00';
var mf_end_time = '11:00:00';
var st_start_time = '10:00:00';
var st_end_time = '12:00:00';
var sn_start_time = '10:00:00';
var sn_end_time = '13:00:00';
var ph_start_time = '10:00:00';
var ph_end_time = '14:00:00';
function time_interval(start,end)
{
var s = strtotime(start);
var e = strtotime(end);
if (s < e)
{
a = e - s;
}
else
{
var e = strtotime('+1 day',e);
var a = e - s;
}
var h = floor(a/3600);
var m = floor((a%3600)/60);
var s = a%60;
return trim((h?h+' hour ':'')+(m?m+' minute ':'')+(s?s+' second ':''));
}
var mf_duration = time_interval(mf_start_time,mf_end_time);
var st_duration = time_interval(st_start_time,st_end_time);
var sn_duration = time_interval(sn_start_time,sn_end_time);
var ph_duration = time_interval(ph_start_time,ph_end_time);
console.log(mf_duration);
console.log(st_duration);
console.log(sn_duration);
console.log(ph_duration);
This does not work because strtotime does not work for Javascript (error not defined). What can I use for that?
I did my best to replicate what your php does, however I don't know if this would be best practice in js, nor if it would be of the same use as you have in your php app. Hopefully this is a good starting point for you to see how js works 👍
var mf_start_time = '10:00:00';
var mf_end_time = '11:00:00';
var st_start_time = '10:00:00';
var st_end_time = '12:00:00';
var sn_start_time = '10:00:00';
var sn_end_time = '13:00:00';
var ph_start_time = '10:00:00';
var ph_end_time = '14:00:00';
function time_interval(start, end) {
var [sHour, sMinute, sSecond] = start.split(":");
var [eHour, eMinute, eSecond] = end.split(":");
var s = new Date();
s.setHours(sHour, sMinute, sSecond);
var e = new Date();
e.setHours(eHour, eMinute, eSecond);
var a;
if (s.getTime() < e.getTime()) {
a = e.getTime() - s.getTime();
} else {
e.setDate(e.getDate() + 1);
a = e.getTime() - s.getTime();
}
a = a / 1000;
var h = Math.floor(a/3600);
var m = Math.floor((a%3600)/60);
var s = a%60;
return (
(h ? h + ' hour ' : '') +
(m ? m +' minute ':'') +
(s ? s +' second ':'')
).trim();
}
var mf_duration = time_interval(mf_start_time, mf_end_time);
var st_duration = time_interval(st_start_time, st_end_time);
var sn_duration = time_interval(sn_start_time, sn_end_time);
var ph_duration = time_interval(ph_start_time, ph_end_time);
console.log(mf_duration);
console.log(st_duration);
console.log(sn_duration);
console.log(ph_duration);
I saw the age-verification snippet solution for my problem and it worked great. But in that solution the occurrence of that popup is based on the number of days. I want the popup to occur every time the user enters my website. How to do it?
Here's is the JS part of the snippet code.
<script>
function ageCheck() {
var min_age = {{ age }}; // Set the minimum age.
var year = parseInt(document.getElementById('byear').value);
var month = parseInt(document.getElementById('bmonth').value);
var day = parseInt(document.getElementById('bday').value);
var theirDate = new Date((year + min_age), month, day);
var today = new Date;
if ((today.getTime() - theirDate.getTime()) < 0) {
window.location = 'http://google.com'; //enter domain url where you would like the underaged visitor to be sent to.
} else {
var days = 1; //number of days until they must go through the age checker again.
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
document.cookie = 'isAnAdult=true;'+expires+"; path=/";
location.reload();
};
};
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
};
var isAnAdult = readCookie('isAnAdult');
if (isAnAdult) {
document.write("<style> #prompt-background { display: none; }</style>");
};
</script>
and the button that function is called on
<button id="submit_birthdate" class="exitbutton" onclick="ageCheck()">Enter</button>
How to modify this code so that the popup appears every time?
I have the following script
function scraper() {
var url = 'http://gpa.shet.com.aspx';
var sss = SpreadsheetApp.getActiveSpreadsheet();
//var ss = SpreadsheetApp.openById('1im78ip4Wcmb1xbfZs8Lqy3-LP1SU9rC8E5OfKbOjJDg');
//var sss = SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = sss.getSheetByName("Sheet1");
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var response = UrlFetchApp.fetch(url);
var contentText = response.getContentText();
var pr = sheet.getRange('A1:Z1000');
var cstring = contentText.tostring;
var ui = SpreadsheetApp.getUi();
var NHL = "New Agent";
var nlength = contentText.length;
// ui.alert(nlength);
//ui.alert(contentText);
//var g = 5;
var clength = 200000;
///
var temp = contentText;
var count = (temp.match(/New Hot Lead/g) || []).length;
var C6 = sheet.getRange('C6');
var C8 = sheet.getRange('C8');
var C10 = sheet.getRange('C10').getValue();
var C10r = sheet.getRange('C10');
if (count > 0) {
var d = new Date();
var hrs = d.getHours();
var mins = d.getMinutes();
var time1 = hrs + ":" + mins;
if (C6.isBlank() == true) {
C6.setValue(time1);
} else if (C6.isBlank() == false) {
C8.setValue(time1);
}
}
if (count == 0) {
C6.clear();
C8.clear();
}
var time2 = 0.00347222222222222;
if (C10 >= time2) {
var D10 = sheet.getRange("D10");
var alert = "NHLs for more than 5 minutes!";
D10.setValue(alert);
D10.setFontColor('Red');
}
}
Now, the problem is not the code itself, since when I run it manually it does work the way it's expected. My problem is with the time-driven trigger. I have tried to manually set it for every minute, and to add the triggerbuilder code at the end and outside of the function, but it still won't work. What are some suggestions?
Try using the sleep function for 60 seconds.
sleep(60000);
How would i pass my current timer's timing into the next page?
Timer code
var expires = new Date();
expires.setSeconds(expires.getSeconds() + 60); // set timer to 60 seconds
var counter = setInterval(timer, 1);
function timer() {
var timeDiff = expires - new Date();
if (timeDiff <= 0) {
clearInterval(counter);
document.getElementById("timer").innerHTML = "00:00";
return;
}
var seconds = new Date(timeDiff).getSeconds();
var milliSeconds = (new Date(timeDiff).getMilliseconds()/10).toFixed(0);
var seconds = seconds < 10 ? "0" + seconds: seconds;
var milliSeconds = milliSeconds < 10 ? "0" + milliSeconds: milliSeconds;
document.getElementById("timer").innerHTML = seconds + ":" + milliSeconds; // watch for spelling
}
I'm using
<h3 style="color: #ff0000; margin: 0; padding: 0; font-size: 100%;font-weight:normal; font-family: robotolight;"> You have <div id="timer"></div> to complete the game!
in my html.
Is there a way to pass div id='timer'> into the next page?
Thanks.
Reloading the page or loading a new page means reloading javascript since it is runs in the context of the current page. There is good way to pass along javascript variables to a new page; it requires some form of data persistence. Cookies and localStorage are two of the most common ways of persisting data client-side.
Client cookies are written to the browser cache and are transparent in HTTP headers. LocalStorage is a newer mechanism but well supported, allowing up to 5MB of browser storage without passing in headers.
In your use case, instead of storing the timer it would probably make sense to store the timestamp when the timer was started. That way it can be recalculated in the next page from this one static start value.
var timerStart;
var expireDate = new Date();
function displayTimer(){
var now = new Date().getTime();
var timerStart = timerStart || cookieTimer();
val timeDiff = now - timerStart;
document.getElementById("timer").innerHTML = timeDiff.toString();
if(timeDiff > expireDate.getTime()) clearInterval(timerInterval);
}
val timerInterval = setInterval(displayTimer, 1);
// Using cookies
function cookieTimer(){
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
}
return "";
}
function setCookie(cname, cvalue, expireDate) {
var d = new Date();
d.setTime(d.getTime() + expireDate.getTime());
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
var timerCookie = getCookie("timer");
if(timerCookie !== "") return new Date(timerCookie).getTime());
else {
setCookie("timer", timerStart, expireDate);
return new Date().getTime();
}
}
// Using localStorage
function localStorageTimer(){
function setLocalStorageObject(key, obj, expireDate){
obj.expires = expireDate.getTime();
localStorage.setItem(key, JSON.stringify(obj));
}
function getLocalStorageObject(key){
val item = localStorage.getItem(key);
if(item) return JSON.parse(item);
else return {};
}
var timerLocal = getLocalStorageObject("timer");
var now = new Date().getTime();
if(timerLocal && timerLocal.startTime && timerLocal.expires > now) return timerLocal.startTime;
else {
setLocalStorageObject("timer", { startTime: now });
return now;
}
}