Cannot get content of div to store locally and load locally - javascript

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.

Related

How do I get my timer to stop, when my 10th and last question has been answered?

The goal I am trying to achieve is to get my timer to stop when all the questions of my quiz has been answered. I have 10 total questions. I have been able to get the timer to start. But getting ot to stop on the click of submit on the 10th question is something I can't figure out.
Let me know if you know what I am doing
StackOverflow said my code was too long... I added my code to codepen. I also included my JS on here.
// variables
var score = 0; //set score to 0
var total = 10; //total nmumber of questions
var point = 1; //points per correct answer
var highest = total * point;
//init
console.log('script js loaded')
function init() {
//set correct answers
sessionStorage.setItem('a1', "b");
sessionStorage.setItem('a2', "a");
sessionStorage.setItem('a3', "c");
sessionStorage.setItem('a4', "d");
sessionStorage.setItem('a5', "b");
sessionStorage.setItem('a6', "d");
sessionStorage.setItem('a7', "b");
sessionStorage.setItem('a8', "b");
sessionStorage.setItem('a9', "d");
sessionStorage.setItem('a10', "d");
}
// timer
// var i = 1;
// $("#startButton").click(function (e) {
// setInterval(function () {
// $("#stopWatch").html(i);
// i++;
// }, 1000);
// });
// $("#resetButton").click(function (e) {
// i = 0;
// });
//hide all questions to start
$(document).ready(function() {
$('.questionForm').hide();
//show question 1
$('#question1').show();
$('.questionForm #submit').click(function() {
//get data attribute
current = $(this).parents('form:first').data('question');
next = $(this).parents('form:first').data('question') + 1;
//hide all questions
$('.questionForm').hide();
//show next question in a cool way
$('#question' + next + '').fadeIn(400);
process('' + current + '');
return false;
});
});
//process answer function
function process(n) {
// get input value
var submitted = $('input[name=question' + n + ']:checked').val();
if (submitted == sessionStorage.getItem('a' + n + '')) {
score++;
}
if (n == total) {
$('#results').html('<h3>Your score is: ' + score + ' out of ' + highest + '!</h3> <button onclick="myScore()">Add Your Name To Scoreboard!</a>')
}
return false;
}
window.yourPoints = function() {
return n;
}
function myScore() {
var person = prompt("Please enter your name", "My First Name");
if (person != null) {
document.getElementById("myScore").innerHTML =
person + " " + score
}
}
// function showTime() {
// var d = new Date();
// document.getElementById("clock").innerHTML = d.toLocaleTimeString();
// }
// setInterval(showTime, 1000);
var x;
var startstop = 0;
window.onload = function startStop() { /* Toggle StartStop */
startstop = startstop + 1;
if (startstop === 1) {
start();
document.getElementById("start").innerHTML = "Stop";
} else if (startstop === 2) {
document.getElementById("start").innerHTML = "Start";
startstop = 0;
stop();
}
}
function start() {
x = setInterval(timer, 10);
} /* Start */
function stop() {
clearInterval(x);
} /* Stop */
var milisec = 0;
var sec = 0; /* holds incrementing value */
var min = 0;
var hour = 0;
/* Contains and outputs returned value of function checkTime */
var miliSecOut = 0;
var secOut = 0;
var minOut = 0;
var hourOut = 0;
/* Output variable End */
function timer() {
/* Main Timer */
miliSecOut = checkTime(milisec);
secOut = checkTime(sec);
minOut = checkTime(min);
hourOut = checkTime(hour);
milisec = ++milisec;
if (milisec === 100) {
milisec = 0;
sec = ++sec;
}
if (sec == 60) {
min = ++min;
sec = 0;
}
if (min == 60) {
min = 0;
hour = ++hour;
}
document.getElementById("milisec").innerHTML = miliSecOut;
document.getElementById("sec").innerHTML = secOut;
document.getElementById("min").innerHTML = minOut;
document.getElementById("hour").innerHTML = hourOut;
}
/* Adds 0 when value is <10 */
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function reset() {
/*Reset*/
milisec = 0;
sec = 0;
min = 0
hour = 0;
document.getElementById("milisec").innerHTML = "00";
document.getElementById("sec").innerHTML = "00";
document.getElementById("min").innerHTML = "00";
document.getElementById("hour").innerHTML = "00";
}
//adding an event listener
window.addEventListener('load', init, false);
https://codepen.io/rob-connolly/pen/xyJgwx
Any help would be appreciated.
its a pretty simple solution just call the stop function in the if condition of n == total
if (n == total) {
$('#results').html('<h3>Your score is: ' + score + ' out of ' + highest + '!</h3>
<button onclick="myScore()">Add Your Name To Scoreboard!</a>')
stop()
}
https://codepen.io/nony14/pen/VwYREgr
Try using clearInterval() to stop the timer.
https://codepen.io/thingevery/pen/dyPrgwz

How can I make my countdown reset every night at 16:00

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.

Coundown cokie set up

I cant figuret how set cookie for my countdownt timeer, that if i refresh page it vill not disapear but vill counting.
i be glad if eny can help. i use jquery 2.1.4 and this java countdown script, but when i refresh page all my coundown timers are lost!
/**
* Created by op on 18.07.2015.
*/
function leadZero (n)
{
n = parseInt(n);
return (n < 10 ? '0' : '') + n;
}
function startTimer(timer_id) {
var timer = $(timer_id);
var time = timer.html();
var arr = time.split(":");
var h = arr[0];
h = h.split(" / ");
h = h[1];
var m = arr[1];
var s = arr[2];
if (s == 0)
{
if (m == 0)
{
if (h == 0)
{
timer.html('')
return;
}
h--;
m = 60;
}
m--;
s = 59;
}
else
{
s--;
}
timer.html(' / '+leadZero(h)+":"+leadZero(m)+":"+leadZero(s));
setTimeout(function(){startTimer(timer_id)}, 1000);
}
function timer (name, time)
{
var timer_name = name;
var timer = $(timer_name);
var time_left = time;
timer.html(' / '+ time);
startTimer(timer_name);
}
$(document).ready(function(){
$('.fid').click(function (e)
{
var timer_name = '.timer_'+$(this).data('fid');
var timer = $(timer_name);
if (timer.html() == '')
{
var time_left = timer.data('timer');
var hours = leadZero(Math.floor(time_left / 60));
var minutes = leadZero(time_left % 60);
var seconds = '00';
timer.html(' / '+hours+':'+minutes+':'+seconds);
startTimer(timer_name);
}
});
$.each($('.tab'), function () {
$(this).click(function () {
$.each($('.tab'), function() {
$(this).removeClass('active');
});
$(this).addClass('active');
$('.list').hide();
$('#content-'+$(this).attr('id')).show();
});
});
if (window.location.hash != '')
{
var tab = window.location.hash.split('-');
tab = tab[0];
$(tab).click();
}
console.log(window.location.hash)
});
It would help if you actually set a cookie.
Setting the cookie would go like:
document.cookie="timer=" + time;
And then call it at the beginning of your code
var time = getCookie("timer");
The getCookie() function is outlined in that link, as well as a base knowledge about them.

I want to make countdown then capatcha

Hi
I got countdown code
<script type="text/javascript">
window.onload = function() {
countDown('my_div1', '<form>1+1=<input name="d" type="text" /></form>', 10);
}
function countDown(elID, output, seconds) {
var elem = document.getElementById(elID),
start = new Date().getTime(), end = start+seconds*1000,
timer = setInterval(function() {
var now = new Date().getTime(), timeleft = end-now, timeparts;
if( timeleft < 0) {
elem.innerHTML = output;
clearInterval(timer);
}
else {
timeparts = [Math.floor(timeleft/60000),Math.floor(timeleft/1000)%60];
if( timeparts[1] < 10) timeparts[1] = "0"+timeparts[1];
elem.innerHTML = "Time left: "+timeparts[1];
}
},250);
}
</script>
I want when the countdown end appear CAPTCHA or question if this right, then continue to link
try to put the countdown function here
window.onload = function() {
countDown('my_div1', //here// , 10);
}
Assume that your countdown coding is working fine and you have a div in which captcha is stored say div id = "captchadiv",
<script type="text/javascript">
window.onload = function() {
//////////////////////////////////////////////////////
set the visibility of the captcha hidden here.
//////////////////////////////////////////////////////
countDown('my_div1', '<form>1+1=<input name="d" type="text" /></form>', 10);
}
function countDown(elID, output, seconds) {
var elem = document.getElementById(elID),
start = new Date().getTime(), end = start+seconds*1000,
timer = setInterval(function() {
var now = new Date().getTime(), timeleft = end-now, timeparts;
if( timeleft < 0) {
elem.innerHTML = output;
clearInterval(timer);
//////////////////////////////////////////////////////
set visibility of captchadiv to visibile.
//////////////////////////////////////////////////////
}
else {
timeparts = [Math.floor(timeleft/60000),Math.floor(timeleft/1000)%60];
if( timeparts[1] < 10) timeparts[1] = "0"+timeparts[1];
elem.innerHTML = "Time left: "+timeparts[1];
}
},250);
}
//////////////////////////////////////////////////////
add a function here to validate the captcha.
If validation succeeds, do success action.
If validation fails, set captcha visibility to hidden and again call the counttDown function.
//////////////////////////////////////////////////////
</script>
EDIT
Check this out. (Untested version)
<script type="text/javascript">
var mathenticate;
window.onload = function() {
countDown('my_div1', '<form>1+1=<input name="d" type="text" /></form>', 10);
}
function countDown(elID, output, seconds) {
var elem = document.getElementById(elID),
start = new Date().getTime(), end = start+seconds*1000,
timer = setInterval(function() {
var now = new Date().getTime(), timeleft = end-now, timeparts;
if( timeleft < 0) {
elem.innerHTML = output;
clearInterval(timer);
mathenticate = {
bounds: {
lower: 5,
upper: 50
},
first: 0,
second: 0,
generate: function()
{
this.first = Math.floor(Math.random() * this.bounds.lower) + 1;
this.second = Math.floor(Math.random() * this.bounds.upper) + 1;
},
show: function()
{
return this.first + ' + ' + this.second;
},
solve: function()
{
return this.first + this.second;
}
};
mathenticate.generate();
var $auth = $('<input type="text" name="auth" />');
$auth
.attr('placeholder', mathenticate.show())
.insertAfter('input[name="name"]');
}
else {
timeparts = [Math.floor(timeleft/60000),Math.floor(timeleft/1000)%60];
if( timeparts[1] < 10) timeparts[1] = "0"+timeparts[1];
elem.innerHTML = "Time left: "+timeparts[1];
}
},250);
}
$('#form').on('submit', function(e){
e.preventDefault();
if( $auth.val() != mathenticate.solve() )
{
alert('wrong answer!');
// If you want to generate a new captcha, then
mathenticate.generate();
}else {
document.location.href = 'http://www.overdir.com';
}
});
</script>

Stop jQuery Typewriter animation onclick

I'm wondering how I might stop the following typewriter script when I - for instance - click a link. I don't want to do anything fancy, simply stop the animation as soon as the link is clicked.
$(function () {
var ch = 0;
var item = 0;
var items = $('.headline_origin li').length;
var time = 1000;
var delay = 40;
var wait = 6000;
var tagOpen = false;
function tickInterval() {
if(item < items) {
var text = $('.headline_origin li:eq('+item+')').html();
type(text);
text = null;
var tick = setTimeout(tickInterval, time);
} else {
clearTimeout(tick);
}
}
function type(text) {
time = delay;
ch++;
if(text.substr((ch - 1), 1) == '<') {
if(text.substr(ch, 1) == '/') {
tagOpen = false;
}
var tag = '';
while(text.substr((ch - 1), 1) != '>') {
tag += text.substr((ch - 1), 1);
ch++;
}
ch++;
tag += '>';
var html = /\<[a-z]+/i.exec(tag);
if(html !== null) {
html = html[0].replace('<', '</') + '>';
tagOpen = html;
}
}
if(tagOpen !== false) {
var t = text.substr(0, ch);
} else {
var t = text.substr(0, ch);
}
$('h1 span.origin').html(t);
if(ch > text.length) {
item++;
ch = 0;
time = wait;
}
}
var tick = setTimeout(tickInterval, time);
});
Thanks in advance!
#rrfive
Inside your tickInterval function, remove the var declaration from the setTimeout - we can reuse the global tick variable.
Then you just need to have a clearInterval(tick); on your click handler for whichever button you like.

Categories

Resources