Need a counter to update daily - javascript

I am looking for a quick script that will update a number daily. This is for something like the number of days without an accident in the work place.
I want it to to put an link to the HTML page for it in the startup group in XP (yes XP, company is a little behind) and have it run at bootup. I may add more stuff later but this is the main purpose.
So each day it needs to update the number by 1 based on the previous days number, so it is most likely going to have to be read and written to a file. If the browser is closed or the system rebooted it should not update increment the browser unless it is a different day.
Can someone point me to a good way of doing this. I was thinking javascript, but I am open. I have no access to a database.
Thanks

This script should do the trick
HTML
<div id="counter">1</div>
<button id="reset">Reset</button>
JS
setInterval(function(){
var value = parseInt(document.getElementById('counter').innerHTML);
document.getElementById('counter').innerHTML = (value+1).toString();
},86400000); //86400000 = 1 day in milliseconds
var btn = document.getElementById('reset');
btn.onclick=function(){
document.getElementById('counter').innerHTML = "0";
};
http://jsfiddle.net/khe67/3/

Well than you may wanna use HTML5 to save variables within the web browser, so if you happen to reload or reboot the computer you still have your variables saved. Code may look something like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Hello HTML5</title>
<script>
window.onload = function (){
if(typeof(Storage)!=="undefined"){
var goodDays;
var oldTime = localStorage.getItem("oldTime");
var timestamp = new Date().getTime();
if(!oldTime || oldTime==""){
goodDays = 1;
localStorage.setItem("oldTime", timestamp);
localStorage.setItem("dayCounter", goodDays);
}else{
var timeCheck = oldTime + (24 * 60 * 60 * 1000);
goodDays = localStorage.getItem("dayCounter");
if(timestamp > timeCheck){
goodDays++;
localStorage.setItem("oldTime", timestamp);
localStorage.setItem("dayCounter", goodDays);
}
}
document.getElementById("dCounter").innerHTML=goodDays;
}else{
alert("geat a real browser");
}
}
function resetDays(){
localStorage.setItem("oldTime", "");
localStorage.setItem("dayCounter", "");
location.reload();
}
</script>
</head>
<body>
<div style="display:inline">DAYS WITH OUT INCENDENTS </div><div style="display:inline" id="dCounter"></div>
<div style="cursor:pointer" onclick="resetDays()">Reset</div>
</body>
</html>

Related

How can I add a date and time clock to a website?

I need to add a date and time clock to a website. It should display the date and time in a very specific format, taking up two lines and using an intended timezone of GMT-4; for example:
Sat, Mar 23 2019
10:33:56 PM
This happens to be for a school project, but I have limited knowledge of Javascript. I've tried looking up some examples and have found some interesting stuff, but I'm unable to adapt those examples to generate the output in the desired format.
Please Try This
function display_c(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}
function display_ct() {
var CDate = new Date()
var NewDate=CDate.toDateString();
NewDate = NewDate + " - " + CDate.toLocaleTimeString();
document.getElementById('ct').innerHTML = NewDate;
display_c();
}
<html>
<head> </head>
<body onload=display_ct();>
<span id='ct' ></span>
</body>
</html>
For Change Date Or Time Format Please Refer this link
Get currentDate by toDateString() method and get current time by toLocaleTimeString and append both in your DOM . And call this every 1000 ms to get updated value .
function callDateTime(){
var currentDate=(new Date()).toDateString();
var currentTime=(new Date()).toLocaleTimeString();
document.getElementById('watch').innerHTML=`${currentDate}-${currentTime}`;
}
setInterval(function(){ callDateTime() }, 1000);
<p id="watch"></p>
You can add an HTML to your the body of your document:
Also, you can add a JavaScript similar to this before </body>:
Code:
function clock(){
window.rt=1000;r=0;
document.getElementById('t-0').textContent=new Date().toLocaleDateString(); // today
var m=setInterval(function(){
if(r>84600){clearInterval(m);}
r++;
document.getElementById('t-2').textContent=new Date().toLocaleTimeString(); // clock
}, window.rt);
}
<!DOCTYPE html>
<html lang="en">
<title>Clock</title>
<body onload="clock();">
<div style="text-align:center;">
📅
<b id="t-0">00/00/0000</b>
⏰
<b id="t-2">00:00:00</b>
</div>
</body>
</html>

Creating simple countdowns in javascript

I've been trying to make a few javascript based countdowns/timers to place around my web site... an example of this would be...
"I’m a 25-year-old part-time blogger & designer and full-time waitress & bartender!" where the "25" would increase every year to update the age.
another example would be...
"with my soon to be husband (COUNTDOWN TILL WEDDING HERE)" and change "soon to be husband" to "husband"
ive seen a few script round but not quite what i need..
I've been trying to use the Math.floor method which works for the amount of days but i need to figure out how to add years. is there a way to calculate years using math.floor?
sidenote * i am not very familiar with javascript or anything of the sort whatsoever
You can use Javascript to do that:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome to My Page!</title>
</head>
<body>
<div id="about-me"></div>
</body>
<script>
function get_message() {
var my_birthday = new Date("2/13/1996"); // update your birthday here
var today = new Date();
var time_diff = Math.abs(today.getTime() - my_birthday.getTime()); // get the difference in milliseconds between today's date and your birthday
var my_age = Math.floor(time_diff / (1000 * 3600 * 24 * 365)); // get your age
var s = document.getElementById('about-me');
var message = "I’m a " + my_age.toString() + "-year-old part-time blogger & designer and full-time waitress & bartender!";
s.innerHTML = message; // update your age
}
window.onload = get_message; // load script only when page is loaded
</script>
</html>
Hope this helps!

How to make a not bootable counter when refreshing the web page?

I want to make a counter remains dynamic and non-bootable when updating
web page,
here is my code the problem is that when I refresh the page the counter(setTimeout) will count again from zero to 5 I want it to count from the last value before
the refresh
<html>
<head>
<meta charset="utf-8"/>
<title>Insert title here</title>
</head>
<script type="text/javascript">
setTimeout(function(){document.getElementById("tm").style.display='block'},
5000);
</script>
<body>
<form id="customer" action="/htmlvalidation" method="post">
<div>
<label>Time</label>
<input id="tm" type="text" style="display: none;"/>
</div>
<div>
<button type="submit">Add Customer</button>
</div>
</form>
</body>
</html>
thank you
You will have to manually store the counter value in the client's browser; by default, browsers will not retain any of a webpage's state when it is closed (or refreshed). For example, you may use the localStorage API:
const STORAGE_KEY = 'counter';
const TARGET_ELEMENT_ID = 'counter-div';
const INTERVAL = 1000;
const INC = 1;
// Notice the '+' below to make sure val is a number.
let val = +localStorage.getItem(STORAGE_KEY) || 0;
document.getElementById(TARGET_ELEMENT_ID).innerHTML = val;
setInterval(() => {
val += INC;
localStorage.setItem(STORAGE_KEY, val);
document.getElementById(TARGET_ELEMENT_ID).innerHTML = val;
}, INTERVAL);
Here is a working example on codepen (it seems stackoverflow's snippets do not support localStorage).
(I didn't use your snippet because I wasn't sure what you were trying to do).
You could store the last timer iteration using localStorage before the user closes or navigates away from the tab, and resume when needed.
More about localStorage

Javascript prompt command executes before the documents writes

I have a problem with the code below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/main.css">
<title>The Ultimate Quiz Challenge</title>
</head>
<body>
<div class="container">
<h1>The Ultimate Quiz Challenge</h1>
<script>
document.write("<h3> " + "Welcome to the ultimate quizz challenge" +"</h3>");
document.write("<p> "+"Hi I will ask you five questions and then rank you" + "</p>");
var question1 ="<p>What is the capital of England</p>";
var firstanswer ="London";
var question2 = "<p>How many sides are there to a square</p>";
var secondanswer = 4;
var noofquestions = 2;
var count = 1
/*var temp = eval('question' +1); */
/*document.write(temp);*/
/* main loop asking questions */
while (count <= 2) {
var temp = eval('question' + count);
document.write(temp);
var answer = prompt("Please type your answer ");
count++;
}
</script>
</div>
</body>
</html>
When I load the file into a browser such a chrome or safari it does not execute as hoped.
In short the document.write commands do not come out onto the screen until the prompt window as asked for two inputs. I thought the first thing to be seen would be the Ultimate Quiz Challenge followed by the commands in the open script tag down to the bottom ?
You should use the onload event on your body, so your script executes once the html page is rendered. It should work with :
<body onload="displayText()">
displayText() being a function you define in your script :
var displayText = function () {
while (count <= 2) {
var temp = eval('question' + count);
document.write(temp);
var answer = prompt("Please type your answer ");
count++;
}
};
or something similar.

Passing a var to another page

Is it possible to pass the totalScore var to another page onclick so that it can be displayed there? ex: click submit link it goes to yourscore.html and display the score on page
$("#process").click(function() {
var totalScore = 0;
$(".targetKeep").each( function(i, tK) {
if (typeof($(tK).raty('score')) != "undefined") {
totalScore += $(tK).raty('score');
}
});
alert("Total Score = "+totalScore);
});
Let we suppose that your HTML may be as follows:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#process").click(function() {
var totalScore = 0;
/*
Your code to calculate Total Score
Remove the next line in real code.
*/
totalScore = 55; //Remove this
alert("Total Score = "+totalScore);
$("#submit-link").attr('href',"http://example.com/yourscore.html?totalScore="+totalScore);
});
});
</script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<button id="process">Process</button>
<br />
Submit Total Score
</body>
</html>
Check out this DEMO
In yourscore.html you may able to know more in the following queation to extract the URL parameter from the URL:
Parse URL with jquery/ javascript?
This is generally done by changing the url of the page. i.e. if you are going go to a new page, just do:
http://example.com/new/page?param1=test
If the page already exists in a new window (like a popup that you own), set the url to something new:
http://example.com/new/page#param
Open a window:
var win = window.open('http://example.com/new/page?totalscore'+totalscore,'window');
Change the location:
win.location.href='http://example.com/new/page?totalscore'+totalscore;
Other ways of doing this could be websockets or cookies or localstorage in HTML5.
if you are aiming to support more modern browsers the elegant solution could be to use sessionStorage or localStorage! Its extremely simple and can be cleared and set as you need it. The maximum size at the low end is 2mb but if your only storing INTs then you should be okay.
DOCS:
http://www.html5rocks.com/en/features/storage
http://dev.w3.org/html5/webstorage/
DEMO:
http://html5demos.com/storage
EXAMPLE:
addEvent(document.querySelector('#local'), 'keyup', function () {
localStorage.setItem('value', this.value);
localStorage.setItem('timestamp', (new Date()).getTime());
//GO TO YOUR NEXT PAGEHERE
});

Categories