I have a JS function to save and load content of a notepad I've made, locally.
I tried to replicate this for a div which contains times of a stopwatch.(see code below)
The stopwatch when paused will write it's time to this div to be saved, I want these times to save when I refresh / close and reopen the page.
It works for my notes in the notepad, please can someone explain where I'm going wrong?
JavaScript for save function:
//Storage of Text-Box
const notesInput = document.querySelector('#notes');
function remFunc() {
// store the entered name in web storage
localStorage.setItem('notes', notes.value);
}
function loadfunc() {
if(localStorage.getItem('notes')) {
let notes_var = localStorage.getItem('notes');
notes.value= notes_var;
} else {
}
}
document.body.onload = loadfunc();
//Storage of Times DIV
const output = document.querySelector('#output');
function remfunc2() {
localStorage.setItem('output', outContent.innerHTML);
}
function loadfunc2() {
if(localStorage.getItem('output')) {
let output_var = localStorage.getItem('output');
output.innerHTML = output_var ;
} else {
}
}
document.body.onload = loadfunc2();
This is the div:
<div id="output" name="output" class="buttonZ logPad"></div>
Here is the stopwatch Javascript:
// Timer JS
var flagclock = 0;
var flagstop = 0;
var stoptime = 0;
var splitcounter = 0;
var currenttime;
var splitdate = '';
var output;
var clock;
function startstop()
{
var startstop = document.getElementById('startstopbutton');
var startdate = new Date();
var starttime = startdate.getTime();
if(flagclock==0)
{
startstop.value = 'Stop';
flagclock = 1;
counter(starttime);
}
else
{
startstop.value = 'Start';
flagclock = 0;
flagstop = 1;
splitdate = '';
logTime();
}
}
function counter(starttime)
{
output = document.getElementById('output');
clock = document.getElementById('clock');
currenttime = new Date();
var timediff = currenttime.getTime() - starttime;
if(flagstop == 1)
{
timediff = timediff + stoptime
}
if(flagclock == 1)
{
clock.innerHTML = formattime(timediff,'');
clock.setAttribute('value', formattime(timediff, ''));
refresh = setTimeout('counter(' + starttime + ');',10);
}
else
{
window.clearTimeout(refresh);
stoptime = timediff;
}
}
function formattime(rawtime,roundtype)
{
if(roundtype == 'round')
{
var ds = Math.round(rawtime/100) + '';
}
else
{
var ds = Math.floor(rawtime/100) + '';
}
var sec = Math.floor(rawtime/1000);
var min = Math.floor(rawtime/60000);
ds = ds.charAt(ds.length - 1);
if(min >= 60)
{
startstop();
}
sec = sec - 60 * min + '';
if(sec.charAt(sec.length - 2) != '')
{
sec = sec.charAt(sec.length - 2) + sec.charAt(sec.length - 1);
}
else
{
sec = 0 + sec.charAt(sec.length - 1);
}
min = min + '';
if(min.charAt(min.length - 2) != '')
{
min = min.charAt(min.length - 2)+min.charAt(min.length - 1);
}
else
{
min = 0 + min.charAt(min.length - 1);
}
return min + ':' + sec + ':' + ds;
}
function resetclock()
{
flagstop = 0;
stoptime = 0;
splitdate = '';
window.clearTimeout(refresh);
if(flagclock !== 0) {
startstopbutton.value = 'Start';
flagclock = 0;
flagstop = 1;
splitdate = '';
}
if(flagclock == 1)
{
var resetdate = new Date();
var resettime = resetdate.getTime();
counter(resettime);
}
else
{
clock.innerHTML = "00:00:0";
}
}
//Split function
function splittime()
{
if(flagclock == 1)
{
if(splitdate != '')
{
var splitold = splitdate.split(':');
var splitnow = clock.innerHTML.split(':');
var numbers = new Array();
var i = 0
for(i;i<splitold.length;i++)
{
numbers[i] = new Array();
numbers[i][0] = splitold[i]*1;
numbers[i][1] = splitnow[i]*1;
}
if(numbers[1][1] < numbers[1][0])
{
numbers[1][1] += 60;
numbers[0][1] -= 1;
}
if(numbers[2][1] < numbers[2][0])
{
numbers[2][1] += 10;
numbers[1][1] -= 1;
}
}
splitdate = clock.innerHTML;
output.innerHTML += (++splitcounter) + '. ' + clock.innerHTML + '\n';
}
}
function logTime() {
const time = document.getElementById('clock').getAttribute('value');
document.getElementById('output').innerHTML += (++splitcounter) + '. ' + time + '<br />';
}
function time() {
splittime();
resetclock();
}
Any help will be much appreciated! Thank you.
Okay, so I figured out what I was doing wrong.
The 'output' variable was being used in the timer code.
This prevented me from setting the variable correctly.
I changed the id for the div and the variable name i was using.
I ran this code in my console on this page and it is working:
let counter = 0;
const outContent = document.querySelector('#notify-container');
setInterval(function()
{
counter++;
outContent.innerHTML = `${counter*2} seconds`;
localStorage.setItem('output', outContent.innerHTML);
}, 2000);
function loadfunc2() {
if(localStorage.getItem('output')) {
let output_var = localStorage.getItem('output');
outContent.innerHTML = output_var ;
counter = parseInt(outContent.innerHTML.split(' ')[0], 10)
}
}
loadfunc2()
Paste it into the console, run it, leave it for a few seconds, then refresh the page, paste it and run it again. You can see it working.
I have a js coding here, but it doesnt work. What is wrong with it?
Am i missing any {}? or what have I written wrong?
window.addEventListener("load", showPage);
function showPage()
console.log("showPage");
document.getElementById('horizontal1').style.animation = 'mymoveHor 1s';
document.getElementById('horizontal2').style.animation = 'mymoveHor 0.5s';
document.getElementById('vertical1').style.animation = 'mymoveVer 1.5s';
var dfade = document.getElementById("portfolio1");
function fadeIn(dfade, time) {
dfade.style.opacity = 0;
var last = +new Date();
var tick = function () {
dfade.style.opacity = +dfade.style.opacity + (new Date() - last) / time;
last = +new Date();
if (+dfade.style.opacity < 1) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
}
};
tick();
}
fadeIn(dfade, 3000);
please help me out...
Just add "{" and "}" to your showPage function
function showPage() {
console.log("showPage");
document.getElementById('horizontal1').style.animation = 'mymoveHor 1s';
document.getElementById('horizontal2').style.animation = 'mymoveHor 0.5s';
document.getElementById('vertical1').style.animation = 'mymoveVer 1.5s';
}
function fadeIn(time) {
var dfade = document.getElementById("portfolio1");
dfade.style.opacity = 0;
var last = +new Date();
var tick = function () {
dfade.style.opacity = +dfade.style.opacity + (new Date() - last) / time;
last = +new Date();
if (+dfade.style.opacity < 1) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
}
};
tick();
}
window.addEventListener("load", showPage);
fadeIn(dfade, 3000);
I am working on a countdown for my website. We provide same day dispatch before 16:00 each day. I need a counter that will display a countdown to 16:00 each day.
Eventually, I will modify the code so that it doesn't display at all on the weekends but for now, all I need is something that can countdown everyday. Disappear after 16:00 and start fresh and countdown again from 00:00
Below is the code I have so far.
<?php
if (new DateTime() < new DateTime("16:00:00")) {
?>
<script type="text/javascript">
var CDown = function() {
this.state=0;// if initialized
this.counts=[];// array holding countdown date objects and id to print to {d:new Date(2013,11,18,18,54,36), id:"countbox1"}
this.interval=null;// setInterval object
}
CDown.prototype = {
init: function(){
this.state=1;
var self=this;
this.interval=window.setInterval(function(){self.tick();}, 1000);
},
add: function(date,id){
this.counts.push({d:date,id:id});
this.tick();
if(this.state==0) this.init();
},
expire: function(idxs){
for(var x in idxs) {
this.display(this.counts[idxs[x]], "Now!");
this.counts.splice(idxs[x], 1);
}
},
format: function(r){
var out="";
if(r.d != 0){out += r.d +" "+((r.d==1)?"day":"days")+", ";}
if(r.h != 0){out += r.h +" "+((r.h==1)?"hour":"hours")+", ";}
out += r.m +" "+((r.m==1)?"min":"mins")+", ";
out += r.s +" "+((r.s==1)?"sec":"secs")+", ";
return out.substr(0,out.length-2);
},
math: function(work){
var y=w=d=h=m=s=ms=0;
ms=(""+((work%1000)+1000)).substr(1,3);
work=Math.floor(work/1000);//kill the "milliseconds" so just secs
y=Math.floor(work/31536000);//years (no leapyear support)
w=Math.floor(work/604800);//weeks
d=Math.floor(work/86400);//days
work=work%86400;
h=Math.floor(work/3600);//hours
work=work%3600;
m=Math.floor(work/60);//minutes
work=work%60;
s=Math.floor(work);//seconds
return {y:y,w:w,d:d,h:h,m:m,s:s,ms:ms};
},
tick: function(){
var now=(new Date()).getTime(),
expired=[],cnt=0,amount=0;
if(this.counts)
for(var idx=0,n=this.counts.length; idx<n; ++idx){
cnt=this.counts[idx];
amount=cnt.d.getTime()-now;//calc milliseconds between dates
// if time is already past
if(amount<0){
expired.push(idx);
}
// date is still good
else{
this.display(cnt, this.format(this.math(amount)));
}
}
// deal with any expired
if(expired.length>0) this.expire(expired);
// if no active counts, stop updating
if(this.counts.length==0) window.clearTimeout(this.interval);
},
display: function(cnt,msg){
document.getElementById(cnt.id).innerHTML=msg;
}
};
window.onload=function(){
var cdown = new CDown();
cdown.add(new Date(2015,9,16,16,00,00), "countbox1");
};
</script>
<span style="font-size:30px;"><div id="countbox1"></div></span>
<?php } ?>
concept here testing
change the variable countDownTo to the current hour on line 8, 103 and 109
change the variable minute on line 133
<?php if (new DateTime() < new DateTime( "16:00:00")) { ?>
<script type="text/javascript">
var check = 0;
/*set the countdown hour*/
var countDownTo = 16;
var CDown = function() {
this.state = 0; // if initialized
this.counts = []; // array holding countdown date objects and id to print to {d:new Date(2013,11,18,18,54,36), id:"countbox1"}
this.interval = null; // setInterval object
}
CDown.prototype = {
init: function() {
this.state = 1;
var self = this;
this.interval = window.setInterval(function() {
self.tick();
}, 1000);
},
add: function(date, id) {
this.counts.push({
d: date,
id: id
});
this.tick();
if (this.state == 0) this.init();
},
expire: function(idxs) {
for (var x in idxs) {
this.display(this.counts[idxs[x]], "Now!");
this.counts.splice(idxs[x], 1);
}
},
format: function(r) {
var out = "";
if (r.d != 0) {
out += r.d + " " + ((r.d == 1) ? "day" : "days") + ", ";
}
if (r.h != 0) {
out += r.h + " " + ((r.h == 1) ? "hour" : "hours") + ", ";
}
out += r.m + " " + ((r.m == 1) ? "min" : "mins") + ", ";
out += r.s + " " + ((r.s == 1) ? "sec" : "secs") + ", ";
return out.substr(0, out.length - 2);
},
math: function(work) {
var y = w = d = h = m = s = ms = 0;
ms = ("" + ((work % 1000) + 1000)).substr(1, 3);
work = Math.floor(work / 1000); //kill the "milliseconds" so just secs
y = Math.floor(work / 31536000); //years (no leapyear support)
w = Math.floor(work / 604800); //weeks
d = Math.floor(work / 86400); //days
work = work % 86400;
h = Math.floor(work / 3600); //hours
work = work % 3600;
m = Math.floor(work / 60); //minutes
work = work % 60;
s = Math.floor(work); //seconds
return {
y: y,
w: w,
d: d,
h: h,
m: m,
s: s,
ms: ms
};
},
tick: function() {
var now = (new Date()).getTime(),
expired = [],
cnt = 0,
amount = 0;
if (this.counts)
for (var idx = 0, n = this.counts.length; idx < n; ++idx) {
cnt = this.counts[idx];
amount = cnt.d.getTime() - now; //calc milliseconds between dates
// if time is already past
if (amount < 0) {
expired.push(idx);
}
// date is still good
else {
this.display(cnt, this.format(this.math(amount)));
}
}
// deal with any expired
if (expired.length > 0) this.expire(expired);
// if no active counts, stop updating
if (this.counts.length == 0) window.clearTimeout(this.interval);
},
display: function(cnt, msg) {
if (msg == `Now!`) {
check = 1;
msg = ``;
var cdown = new CDown();
var currentdate = new Date();
var year = currentdate.getFullYear();
var month = currentdate.getMonth();
var day = currentdate.getDate() + 1;
var currenthour = currentdate.getHours();
/*perform check here*/
if (countDownTo == 16) {
countDownTo = 0;
} else {
countDownTo = 16;
}
var hour = countDownTo;
var minute = 0;
var second = 0;
cdown.add(new Date(year, month, day, hour, minute, second), "countbox1");
} else {
check = 0;
}
if (countDownTo == 0) msg = ``;
document.getElementById(cnt.id).innerHTML = msg;
}
};
window.onload = function() {
var cdown = new CDown();
var currentdate = new Date();
var year = currentdate.getFullYear();
var month = currentdate.getMonth();
var day = currentdate.getDate();
var hour = countDownTo;
var minute = 0;
var second = 0;
cdown.add(new Date(year, month, day, hour, minute, second), "countbox1");
};
</script>
<span style="font-size:30px;"><div id="countbox1"></div></span>
<?php } ?>
You can use a cron job that will reset a variable once every 24 hours.
Try to make a timer like following way:
HTML:
<div id="timer">
<span id="minute" class="dis">00</span> :
<span id="second" class="dis">00</span> :
<span id="milisecond" class="dis">00</span>
</div>
<input type="button" value="Start/Stop" id="startStop" />
<input type="button" value="Reset" id="reset" />
jQuery:
var a = false,
t = null,
ms = 0,
s = 0,
m = 0,
dl = 10,
now = null,
before = new Date(),
El = function(id) { return document.getElementById(id);};
function dsp() {
if(ms++ == 99){
ms = 0;
if(s++ == 59) {
s = 0;
m++;
} else s = s;
} else ms = ms;
El('milisecond').innerHTML = ms
El('second').innerHTML = s < 10 ? '0' + s : s;
El('minute').innerHTML = m < 10 ? '0' + m : m;
}
function r() {
a = true;
var els = document.getElementsByClassName('dis');
ms = s = m = 0;
sw();
for(var i in els) {
els[i].innerHTML = '00';
}
}
function sw() {
a ? clearInterval(t) : t = setInterval(dsp, dl);
a = !a;
}
El('startStop').addEventListener('click', sw, true);
El('reset').addEventListener('click', r, true);
It works just fine. But problem is that it stop execution when window switch or tab change happen. Before submit this question I read this thread, but fail to implement it in my snippet.
Please help me with some solution or suggestion..
Here is the fiddle
Capture the start time (see Marc's comment) and keep track of previous runs (offset):
var a = false;
var dl = 10;
var El = function(id) { return document.getElementById(id);};
var start = null; // starting time of current measurement
var offset = 0; // offset for previous measurement
function dsp() {
var tmp = new Date(new Date() - start + offset ); // calculate the time
var ms = tmp.getMilliseconds();
var m = tmp.getMinutes();
var s = tmp.getSeconds();
El('milisecond').innerHTML = ms;
El('second').innerHTML = s < 10 ? '0' + s : s;
El('minute').innerHTML = m < 10 ? '0' + m : m;
}
function r() {
a = true;
var els = document.getElementsByClassName('dis');
sw();
offset = 0; // Clear the offset
for(var i in els) {
els[i].innerHTML = '00';
}
}
function sw() {
if(a){
// If the timer stops save the current value
offset += (new Date()) - start;
}else
start = new Date();
a ? clearInterval(t) : t = setInterval(dsp, dl);
a = !a;
}
document.getElementById('startStop').addEventListener('click', sw, true);
document.getElementById('reset').addEventListener('click', r, true);
JSFiddle
I got a script which works in IE and chrome but not in FF.. Or it works in all three if I unescape the line where 'x' is alerted!?
in FF 3.6 the div is first visible when the script is half done.. it just jumps to the middle of the "moving line"
<div id="tst" style="position:absolute; top:200px; left:200px; height:100px; width:100px; background:#ff0000"></div>
<script type="text/javascript">
function Tween(){
this.time = 0;
this.duration = 800;
this.x_start = 0;
this.x_end = 0;
this.target_func = null;
this.method_func = null;
this.loop = null;
this.interval = 20;
this.start = function(){
if(!this.method_func){
this.method_func = this.regularEaseOut;
}
var _this = this;
this.loop = setInterval(function(){
if(_this.set_time() > 0){
var x = _this.method_func();
//alert(x);
_this.target_func(x);
}
}, this.interval);
};
this.set_time = function(){
this.time += this.interval;
if(this.time > this.duration){
clearInterval(this.loop);
this.time = 0;
}
return this.time;
};
this.regularEaseInOut = function(){
var t = this.time;
var s = this.x_start;
var e = this.x_end;
var d = this.duration;
if((t/=d/2) < 1){
return c/2*t*t + b;
}
else{
return -c/2 * ((--t)*(t-2) - 1) + b;
}
};
this.regularEaseIn = function(){
var t = this.time;
var s = this.x_start;
var e = this.x_end;
var d = this.duration;
return c*(t/=d)*t + b;
};
this.regularEaseOut = function(){
var t = this.time;
var s = this.x_start;
var e = this.x_end;
var d = this.duration;
return -e *(t/=d)*(t-2) + s;
};
}
var Tween = new Tween();
Tween.x_start = 200;
Tween.x_end = 1200;
Tween.target_func = function(x){
document.getElementById('tst').style.left = x+'px';
};
Tween.start();
</script>
This works:
<html>
<head>
<script type="text/javascript">
function Tween(){
this.time = 0;
this.duration = 800;
this.x_start = 0;
this.x_end = 0;
this.target_func = null;
this.method_func = null;
this.loop = null;
this.interval = 20;
this.start = function(){
if(!this.method_func){
this.method_func = this.regularEaseOut;
}
var _this = this;
this.loop = setInterval(function(){
if(_this.set_time() > 0){
var x = _this.method_func();
//alert(x);
_this.target_func(x);
}
}, this.interval);
};
this.set_time = function(){
this.time += this.interval;
if(this.time > this.duration){
clearInterval(this.loop);
this.time = 0;
}
return this.time;
};
this.regularEaseInOut = function(){
var t = this.time;
var s = this.x_start;
var e = this.x_end;
var d = this.duration;
if((t/=d/2) < 1){
return c/2*t*t + b;
}
else{
return -c/2 * ((--t)*(t-2) - 1) + b;
}
};
this.regularEaseIn = function(){
var t = this.time;
var s = this.x_start;
var e = this.x_end;
var d = this.duration;
return c*(t/=d)*t + b;
};
this.regularEaseOut = function(){
var t = this.time;
var s = this.x_start;
var e = this.x_end;
var d = this.duration;
return -e *(t/=d)*(t-2) + s;
};
}
function doYourThing() {
var tween = new Tween();
tween.x_start = 200;
tween.x_end = 1200;
tween.target_func = function(x){
document.getElementById('tst').style.left = x+'px';
};
tween.start();
}
</script>
</head>
<body onload="doYourThing()">
<div id="tst" style="position:absolute; top:200px; left:200px; height:100px; width:100px; background:#ff0000"></div>
</body>
</html>
So using onload makes sure the method is only run once the document is loaded. Also, you made an instance variable (Tween) with the same name as the "class" you want to instantiate. That will definitely cause you pain and misery down the road.
The alert stops the execution of the code until Ok is pressed. Check if this can be the source of your problems.
What does it mean not works?
if you mean it's not moving to the right, It works for me in my FF 4.0.1