how to add to an HTML time element - javascript

How can I use javascript to add to an existing HTML Time element. I have an html time element and want to be able to press a button that adds one minute to the current time. I don't want to use input type time. This is my existing code:
<body>
<time id = 'time'> 10:00 </time>
<button onclick = "addTime();">addTime</button>
<script>
function addTime(){
document.getElementById('time').innerHTML += '01:00'
}
</script>
</body>
but this just appends the time as a string. Is there an easy way to fix this?

You can use Date.prototype.setMinutes() with first two numbers of .innerHTML of element, Date.prototype.setSeconds() with parameter 0
<body>
<time id='time'> 10:00 </time>
<button onclick="addTime();">addTime</button>
<script>
const time = document.getElementById('time')
let date = new Date();
function addTime() {
date.setMinutes(1 + +time.innerHTML.match(/\d{2}/)[0]);
date.setSeconds(0);
time.innerHTML = String(date).slice(19, 24);
}
</script>
</body>

In html you can put this code:
<time id='time'> <label id="hour">10</label>:<label id="second">00</label> </time>
<button onclick="addTime();">addTime</button>
You can run this function:
function addTime() {
var h = parseInt(document.getElementById('hour').innerHTML);
var s = parseInt(document.getElementById('second').innerHTML);
s++;
var add = "0";
if (s < 10) {
add = "0" + s;
}
else {
add = s;
}
if (s == 60) {
add = "00";
h = h + 1;
}
if (h == 25) {
h = 1;
}
document.getElementById('hour').innerHTML = h;
document.getElementById('second').innerHTML = add;
}

Related

Show Date.getTime() javascript into html

I am trying to make a stopwatch using html and javascript on my website.
Here is what I tried:
<!DOCTYPE HTML>
<html>
<script>
Date.setTime(0);
</script>
<body>
<p>Time: <script>document.write(Date.getTime());</script></p>
</body>
</html>
I want it to show milliseconds since load. I'm doing it on KhanAcademy. Does anybody know how to do this?
Also, somewhat, weirdly, there are no errors
If you want to show the milliseconds since the page load you need to update it using setInterval()
<!DOCTYPE HTML>
<html>
<body>
<p>Time: <span id="msec"></span> </p>
</body>
<script>
var msec = 0;
msec = setInterval(function(){
msec = msec + 1;
document.getElementById("msec").innerText = msec;
},1)
</script>
</html>
You likely meant to do this
NOTE the script tags have to be AFTER the span - it needs to exist.
let d = new Date();
d.setTime(1000)
const span = document.getElementById("time");
const tId = setInterval(function() {
if (d.getTime() <= 0) clearInterval(tId);
span.textContent = d.getTime();
d.setTime(d.getTime() - 10)
}, 10);
<span id="time"></span>
but that is the same as doing this
let d = 1000;
const span = document.getElementById("time");
const tId = setInterval(function() {
span.textContent = d-=10
if (d <= 0) clearInterval(tId);
}, 10)
<span id="time"></span>
Using the window load event so the script can stay in the head
Herre I am counting up
window.addEventListener("load", function() { // on page load
let d = 0;
const span = document.getElementById("time");
const tId = setInterval(function() {
span.textContent = d += 10
if (d >= 1000) clearInterval(tId);
}, 10);
});
<span id="time"></span>
You have to set an interval to update calculate the duration since starting the website (I choose 1 ms). The script has to be written in the code after the HTML-element is declared.
var start = performance.now();
setInterval(function() {
let time = performance.now();
document.getElementById('duration').innerHTML = 'Dauer: ' + (time - start) + ' ms.';
}, 1);
<div id='duration'></div>

writing a tag after cleartimeout in js

This is the code for countdown. After countdown I need to show a hyperlink
<a id="hi" href="page.html">click</a> to users.assuming Eventtime today or you can change it there. How can I do this?
Please correct this code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="days" style="display:inline;">00</p> Days
<p id="hours" style="display: inline;">00</p> Hrs
<p id="minutes" style="display: inline;">00 </p> Min
<p id="seconds" style="display: inline;">00</p> seconds Left
<div id="hi"></div>
<script type="text/javascript">
var timer;
function myLoop() {
var now = new Date();
var eventDate = new Date(2017, 9, 21,7,56);
var currentTime = now.getTime();
var eventTime = eventDate.getTime();
var remTime = eventTime - currentTime;
var s = Math.floor(remTime / 1000);
var m = Math.floor(s/60);
var h = Math.floor(m/60);
var d = Math.floor(h/24);
h %= 24;
m %= 60;
s %= 60;
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
if(d>=0 && h>=0 && m>=0 && s>=0)
{
document.getElementById("days").textContent = d;
document.getElementById("hours").textContent = h;
document.getElementById("minutes").textContent = m;
document.getElementById("seconds").textContent = s;
if(d>=0 && h>=0 && m>=0 && s>=0)
{
timer= setTimeout(myLoop, 1000);
}
else
{
clearTimeout(timer);
document.getElementById('hi').innerHTML=
"<a id='hi'href='page.html'>click</a>";
}
}
}
myLoop();
</script>
</body>
</html>
So how do I set a hyperlink after a cleartimeout. I tried just before clearTimeout statement still not working. Actually, I have to show this anchor tag inside a division which redirects the division to given hyperlink after counter timeout.

How to I auto-update a clock in Javascript? [duplicate]

This question already has answers here:
Run JavaScript function at regular time interval
(4 answers)
setInterval using a non anonymous function requiring parameters has to be inside an anonymous function. Why?
(4 answers)
Closed 6 years ago.
I am trying to make a simple web based clock app using pure java-script. I think the general code is right, but I'm not sure how to automatically call the function at a set interval of time. I thought the window.onload, followed by the setInterval method would do this. But it's not automatically updating every half second as I expected. What am I doing wrong?
<!doctype html>
<html>
<head>
<title>Real Time Clock</title>
<script>
var time, h, m, s, track;
track = 0;
window.onload = function() { setInterval( timeNow(), 100); }
function timeNow() {
time = new Date();
track += 1;
h = time.getHours();
m = time.getMinutes();
s = time.getSeconds();
if ( s < 10 ) { s = "0" + s; } /* we add a 0 in front of s, when it is lower than 10, because that's what most clocks display, this is for the human user rather than for any need by the computer */
document.getElementById("time").innerHTML = h + ':' + m + ':' + s;
document.getElementById("track").innerHTML = track;
}
</script>
</head>
<body>
<span id="time">~Waiting for time update.</span><br>
<span id="track"></span>
</body>
</html>
Seems to work fine. Just needed to change
window.onload = function() { setInterval( timeNow(), 100); }
to
window.onload = function() { setInterval( timeNow, 100); }
<!doctype html>
<html>
<head>
<title>Real Time Clock</title>
<script>
var time, h, m, s, track;
track = 0;
window.onload = function() { setInterval( timeNow, 100); }
function timeNow() {
time = new Date();
track += 1;
h = time.getHours();
m = time.getMinutes();
s = time.getSeconds();
if ( s < 10 ) { s = "0" + s; } /* we add a 0 in front of s, when it is lower than 10, because that's what most clocks display, this is for the human user rather than for any need by the computer */
document.getElementById("time").innerHTML = h + ':' + m + ':' + s;
document.getElementById("track").innerHTML = track;
}
</script>
</head>
<body>
<span id="time">~Waiting for time update.</span><br>
<span id="track"></span>
</body>
</html>
use setInterval(timeNow,100); instead of setInterval(timeNow(),100);
var time, h, m, s, track;
track = 0;
window.onload = function() {
var start = setInterval(timeNow,100);
}
function timeNow() {
var time = new Date();
track += 1;
h = time.getHours();
m = time.getMinutes();
s = time.getSeconds();
if ( s < 10 ) { s = "0" + s; }
document.getElementById("time").innerHTML = h + ':' + m + ':' + s;
document.getElementById("track").innerHTML = track;
}
<span id="time">~Waiting for time update.</span><br>
<span id="track"></span>
You are passing an undefined (as the result of calling timeNow) to setInterval. You need to pass the function, so the code will be:
window.onload = function() { setInterval(timeNow, 100); }

Having trouble with Javascript Stopwatch

I'm working on a stopwatch, and this is my code for it. It makes perfect sense for me, but doesn't want to update for some reason.
HTML:
<ul>
<li id="hour">0</li>
<li>:</li>
<li id="min">0</li>
<li>:</li>
<li id="sec">0</li>
</ul>
JS:
var sec = document.getElementById("sec").value,
min = document.getElementById("min").value,
hour = document.getElementById("hour").value;
function stopWatch(){
sec++;
if(sec > 59) {
sec = 0;
min++;
} else if(min > 59){
min = 0;
hour++;
}
window.setTimeout("stopWatch()", 1000);
}
stopWatch();
A list item has no .value property. Inputs or textareas have. It should be
var sec = parseInt(document.getElementById("sec").innerHTML, 10),
min = parseInt(document.getElementById("min").innerHTML, 10),
hour = parseInt(document.getElementById("hour").innerHTML, 10);
which is also parsing them into numbers.
Also, don't pass a string to setTimeout. Pass the function you want to be called:
window.setTimeout(stopWatch, 1000);
And nowhere in your code you are outputting the updated variables. They are no magic pointers to the DOM properties, but just hold numbers (or strings in your original script).
Last but not least there's a logic error in your code. You are checking whether the minutes exceed 59 only when the seconds didn't. Remove that else before the if.
1) List items LI don't have values, they have innerHTML.
var sec = document.getElementById("sec").innerHTML; (not .value)
2) Nowhere in your code do you set the contents of your LIs. JavaScript doesn't magically associate IDs with variables - you have to do that bit yourself.
Such as:
document.getElementById("hour").innerHTML = hour;
3) Never pass a timeout as a string. Use an anonymous function:
window.setTimeout(function() {stopWatch()}, 1000);
or, plainly:
window.setTimeout(stopWatch, 1000);
(function() {
var sec = document.getElementById("sec").value,
min = document.getElementById("min").value,
hour = document.getElementById("hour").value;
function stopWatch(){
sec++;
if(sec > 59) {
sec = 0;
min++;
} else if(min > 59){
min = 0;
hour++;
}
document.getElementById("sec").textContent = sec
document.getElementById("min").textContent = min
document.getElementById("hour").textContent = hour
window.setTimeout(stopWatch, 1000);
}
stopWatch();
})();
The invocation should only be
window.setInterval(stopWatch, 1000);
So to use the stopwatch, put the function inside:
var sec = 0, min = 0, hour = 0;
window.setInterval(function () {
"use strict";
sec++;
if (sec > 59) {
sec = 0;
min++;
} else if (min > 59) {
min = 0;
hour++;
}
document.getElementById("sec").innerHTML = sec;
document.getElementById("min").innerHTML = hour;
document.getElementById("hour").innerHTML = hour;
}, 1000);
Li elements has no value propertie, use innerHTML.
You could store the values for sec, min & hour in variables.
It is a nice idea to store the setTimeout() call to a variable in case you want to stop the clock later. Like "pause".
http://jsfiddle.net/chepe263/A3a9m/4/
<html>
<head>
<style type="text/css">
ul li{
float: left;
list-style-type: none !important;
}
</style>
<script type="text/javascript">//<![CDATA[
window.onload=function(){
var sec = min = hour = 0;
var clock = 0;
stopWatch = function(){
clearTimeout(clock);
sec++;
if (sec >=59){
sec = 0;
min++;
}
if (min>=59){
min=0;
hour++;
}
document.getElementById("sec").innerHTML = (sec < 10) ? "0" + sec : sec;
document.getElementById("min").innerHTML = (min < 10) ? "0" + min : min;
document.getElementById("hour").innerHTML = (hour < 10) ? "0" + hour : hour;
clock = setTimeout("stopWatch()",1000); }
stopWatch();
pause = function(){
clearTimeout(clock);
return false;
}
play = function(){
stopWatch();
return false;
}
reset = function(){
sec = min = hour = 0;
stopWatch();
return false;
}
}//]]>
</script>
</head>
<body>
<ul>
<li id="hour">00</li>
<li>:</li>
<li id="min">00</li>
<li>:</li>
<li id="sec">49</li>
</ul>
<hr />
Pause
Continue
Reset
</body>
</html>
This is my complete code, this may help you out:
<html>
<head>
<title>Stopwatch Application ( Using JAVASCRIPT + HTML + CSS )</title>
<script language="JavaScript" type="text/javascript">
var theResult = "";
window.onload=function() { document.getElementById('morefeature').style.display = 'none'; }
function stopwatch(text) {
var d = new Date(); var h = d.getHours(); var m = d.getMinutes(); var s = d.getSeconds(); var ms = d.getMilliseconds();
document.stopwatchclock.stpwtch.value = + h + " : " + m + " : " + s + " : " + ms;
if (text == "Start") {
document.stopwatchclock.theButton.value = "Stop";
document.stopwatchclock.theButton.title = "The 'STOP' button will save the current stopwatch time in the stopwatch history, halt the stopwatch, and export the history as JSON object. A stopped stpwatch cannot be started again.";
document.getElementById('morefeature').style.display = 'block';
}
if (text == "Stop") {
var jsnResult = arrAdd();
var cnt = 0; var op= 'jeson output';
for (var i = 0; i < jsnResult.length; i++) {
if (arr[i] !== undefined) {
++cnt; /*json process*/
var j={ Record : cnt, Time : arr[i]};
var dq='"';
var json="{";
var last=Object.keys(j).length;
var count=0;
for(x in j){ json += dq+x+dq+":"+dq+j[x]+dq; count++;
if(count<last)json +=",";
}
json+="}<br>";
document.write(json);
}
}
}
if (document.stopwatchclock.theButton.value == "Start") { return true; }
SD=window.setTimeout("stopwatch();", 100);
theResult = document.stopwatchclock.stpwtch.value;
document.stopwatchclock.stpwtch.title = "Start with current time with the format (hours:mins:secs.milliseconds)" ;
}
function resetIt() {
if (document.stopwatchclock.theButton.value == "Stop") { document.stopwatchclock.theButton.value = "Start"; }
window.clearTimeout(SD);
}
function saveIt() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value; value++;
document.getElementById('number').value = value;
var resultTitle = '';
if(value == '1'){ resultTitle = "<h3>History</h3><hr color='black'>"; }
var objTo = document.getElementById('stopwatchresult')
var spanTag = document.createElement("span");
spanTag.id = "span"+value;
spanTag.className ="stopWatchClass";
spanTag.title ="The stopwatch showing current stopwatch time and a history of saved times. Each saved time are shown as total duration (split time - stopwatch start time) and a lap duration (split time - previous split time). And durations are shown in this format: 'hours:mins:secs.milliseconds'";
spanTag.innerHTML = resultTitle +"<br/><b>Record " + value+" =</b> " + theResult + "";
objTo.appendChild(spanTag);
arrAdd(theResult);
return;
}
var arr = Array();
function arrAdd(value){ arr.push(value); return arr;}
</script>
<style>
center {
width: 50%;
margin-left: 25%;
}
.mainblock {
background-color: #07c1cc;
}
.stopWatchClass {
background-color: #07c1cc;
display: block;
}
#stopwatchclock input {
margin-bottom: 10px;
width: 120px;
}
</style>
</head>
<body>
<center>
<div class="mainblock">
<h1><b title="Stopwatch Application ( Using JAVASCRIPT + HTML + CSS )">Stopwatch Application</b></h1>
<form name="stopwatchclock" id="stopwatchclock">
<input type="text" size="16" class="" name="stpwtch" value=" 00 : 00 : 00 : 00" title="Initially blank" />
<input type="button" name="theButton" id="start" onClick="stopwatch(this.value);" value="Start" title="The 'START' button is start the stopwatch. An already started stopwatch cannot be started again." /><br />
<div id="morefeature">
<input type="button" value="Reset" id="resetme" onClick="resetIt();reset();" title="Once you will click on 'RESET' button will entirely reset the stopwatch so that it can be started again." />
<input type="button" name="saver" id="split" value="SPLIT" onClick="saveIt();" title="The 'SPLIT' button will save the current stopwatch time in the stopwatch history. The stopwatch will continue to progress after split." />
<div>
<input type="hidden" name="number" id="number" value="0" />
</form>
</div>
<div id="stopwatchresult"></div>
</center>
</body>

Clock in Javascript

I have made a clock in javascript but its a static clock. What changes I need to do in the following code so that it updates with every second.
<html>
<head>
<title>Javascript Clock</title>
<script type="text/javascript">
function clk() {
var a=new Date();
document.getElementById("disp").innerHTML=a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds() ;
}
</script>
</head>
<body>
<input type="button" onclick="clk()" value="Display Clock" />
<p id="disp">Clock Space</p>
</body>
</html>
You can use setInterval to run your clk() function every second:
setInterval(clk, 1000); // run clk every 1000ms
MDN on setInterval
As nnnnnn points out, the timer interval probably won't be synchronized with the passage of an actual, real-time second, so using an interval like 100ms might not be a bad idea.
You can add setTimeout(clk,1000); to your function,as bellow:
function clk() {
var a=new Date();
document.getElementById("disp").innerHTML=a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds() ;
setTimeout(clk,1000);
}
A JavaScript digital clock from system time, can also manually set. :-)
function timer(h,m,s){
var sec;
var min;
var hrs;
var day;
if(((s<=59) && (s>=0)) && ((m<=59) && (m>=0)) && ((h<=23) && (h>=0))){
sec=s;
min=m;
hrs=h;
//set parent element id 'lga' to your id
var parent = document.getElementById('lga');
parent.innerHTML = '';
var child = document.createElement('div');
child.id = "thanesh";
child.style = 'font-size:20px';
parent.appendChild(child);
setInterval(function(){
sec++;
if(sec==60){sec=0;min++;}
if(min==60){min=0;hrs++;}
if(hrs==24){hrs = 0; min = 0; sec = 0;}
if(hrs<=12){
day = 'AM';
}else{
day = 'PM';
}
document.getElementById('thanesh').innerHTML = '<table style="background-color:#f5f5f5;"><tr><td><div id="hh">0</div><td>'
+hrs+' : <td><div id="mm">0</div><td>'
+min+' : <td><div id="ss">0</div><td>'
+sec+' <td>'
+day+'</td></td></td></td></td></td></td></tr></table>';
if(sec>9){
document.getElementById('ss').style.display = "none";
}else if(sec==0){
document.getElementById('ss').style.display = "block";
}
if(min>9){
document.getElementById('mm').style.display = "none";
}else if(min==0){
document.getElementById('mm').style.display = "block";
}
if(hrs>9){
document.getElementById('hh').style.display = "none";
}else if(hrs==0){
document.getElementById('hh').style.display = "block";
}
},
1000);
}else{
alert("Check time inputs...!");
}
}
//Set Hour, Minutes, Seconds by JS / manually
var date = new Date();
var hst = date.getHours();
var mst = date.getMinutes();
var sst = date.getSeconds();
timer(hst,mst,sst);
Since your "update every second" of the real clock competes with other computer tasks, the delay before the next real clock tic will be less than 1000 ms very often. So, better use setTimeout instead of setInterval. In fact, we just need to twist a little bit the end of the denied 姚先进's solution here arround, resulting in:
function clk() {
var a=new Date();
document.getElementById("disp").innerHTML=a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds() ;
setTimeout(clk, 1000 - a % 1000);
}
This is my clock solution since 2007.
here we go
<html>
<head>
<title>Javascript Clock</title>
<script type="text/javascript">
function clk() {
setInterval(() => {
var a = new Date();
document.getElementById("disp").innerHTML = a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds();
},1000);
}
</script>
</head>
<body>
<input type="button" onclick="clk()" value="Display Clock" />
<p id="disp">Clock Space</p>
</body>
</html>

Categories