<script type="text/javascript">
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
<td><button type="button" onclick="onClick()" >0.1</td>
<p>Ball Count: <a id="clicks">0.0</a></p>
Hi I am trying to create customized click counter, when every 6th click it should go to the next whole number( Example: 0.1,0.2,0.3,0.4,0.5,1.0 (6th click),1.1,1.2,1.3,1.4,1.5,2.0(12th click) like wise) and how to decrease the same way... Kindly help me.....
Your requirement have some similarities to the time calculation. You can use the following.
jQuery version
var clicks = 0;
$('#plusClick, #minusClick').on('click', function () {
if( this.id == 'plusClick' )
clicks += 10;
else if( clicks > 0 )
clicks -= 10;
var first = Math.floor((clicks) / 60);
var second = clicks - (first * 60);
if (first < 10) {first = "0" + first;}
if (second < 10) {second = "0" + second;}
var value = first + '.' + second;
document.getElementById("clicks").innerHTML = parseFloat(value).toFixed(1);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="clicks">0.0</div>
<button id="minusClick">-</button>
<button id="plusClick">+</button>
JS version
var clicks = 0;
function onClick(operation) {
if( operation ){
clicks += 10;
} else if(clicks > 0){
clicks -= 10;
}
var first = Math.floor((clicks) / 60);
var second = clicks - (first * 60);
if (first < 10) {first = "0" + first;}
if (second < 10) {second = "0" + second;}
var value = first + '.' + second;
document.getElementById("clicks").innerHTML = parseFloat(value).toFixed(1);
}
<div id="clicks">0.0</div>
<button id="minusClick" onclick="onClick(false)">-</button>
<button id="plusClick" onclick="onClick(true)">+</button>
May be you are looking for something like this:
var a = 0;
function increase() {
if (a % 10 == 5)
a += 5;
else
a++;
return a / 10;
}
function decrease() {
if (a % 10 == 0)
a -= 5;
else
a--;
return a / 10;
}
Note that I have used a Global Variable for this, which is not recommended.
Snippet, without global values.
var counter = {
currentValue: 0
};
function increase() {
var a = counter.currentValue;
if (a % 10 == 5)
a += 5;
else
a++;
counter.currentValue = a;
return a / 10;
}
function decrease() {
var a = counter.currentValue;
if (a % 10 == 0)
a -= 5;
else
a--;
counter.currentValue = a;
return a / 10;
}
input {border: 1px solid #999; padding: 5px; width: 15px; height: 15px; text-align: center; font-family: 'Segoe UI'; line-height: 1; width: 50px;}
input[type=button] {padding: 0; vertical-align: top; width: 35px; height: 27px;}
<input type="button" value="-" onclick="currentCount.value = decrease();" />
<input type="text" id="currentCount" value="0" />
<input type="button" value="+" onclick="currentCount.value = increase();" />
Just change onclick() with
function onClick(){
clicks += 1;
var a = Math.floor(clicks/6);
var b = (clicks%6);
document.getElementById("clicks").innerHTML = a + '.' + b;
}
Try to make use of mathematics not some school boy logic,
function increment(val) {
++val;
$("button").data("count", val);
return (val + (Math.floor((val / 6)) * 4)) / 10;
}
$("button").click(function () {
$('input').val(increment(parseFloat($(this).data("count"))));
});
DEMO
Related
How to save a time value in dynamically created li to input box with javascript
I have a simple timer, that starts, stops, pauses, takes a time snap and resets the time snap.
The timesnap in generated and displayed in the webpage inside a li. It all works fine what I am struggling with is trying to click on a displayed time snap and have the value placed in an input box so I can later save a selected value to a database.
This is the script I am using to place the clicked on li item into the input box
var items = document.querySelectorAll("#list li");
for (var i = 0; i < items.length; i++) {
items[i].onclick = function () {
document.getElementById("inptSnap").value = this.innerHTML;
};
}
This is the html
<div class="container">
<!-- Different App -->
<div class="timeDisplay">00:00:00</div>
<button id="begin">Start</button>
<button id="hold">Pause</button>
<button id="end">Stop</button>
<button id="timeSnap">Time Snap</button>
<button id="resetSnap">Reset Time Snap</button>
<ul id="list" class="laps"></ul>
<div>
<input type="text" id="inptSnap" />
</div>
</div>
This is the full timer script with the attempted select value onclick
var begin = document.getElementById("begin");
begin.addEventListener("click", start);
var end = document.getElementById("end");
end.addEventListener("click", stop);
var hold = document.getElementById("hold");
hold.addEventListener("click", pause);
var timeSnap = document.getElementById("timeSnap");
timeSnap.addEventListener("click", snap);
var timeSnap = document.getElementById("timeSnap");
timeSnap.addEventListener("click", pause);
var resetSnap = document.getElementById("resetSnap");
resetSnap.addEventListener("click", resetSnaps);
var ms = 0,
s = 0,
m = 0;
var timeCounter;
var displayEl = document.querySelector(".timeDisplay");
var lapsContainer = document.querySelector(".laps");
function start() {
if (!timeCounter) {
timeCounter = setInterval(run, 10);
}
}
function run() {
displayEl.textContent = displayTimeCount();
ms++;
if (ms == 100) {
ms = 0;
s++;
}
if (s == 60) {
s = 0;
m++;
}
}
function stop() {
stopTimer();
ms = 0;
s = 0;
m = 0;
displayEl.textContent = displayTimeCount();
}
function stopTimer() {
clearInterval(timeCounter);
timeCounter = false;
}
function pause() {
stopTimer();
}
function displayTimeCount() {
return (
(m < 10 ? "0" + m : m) +
":" +
(s < 10 ? "0" + s : s) +
":" +
(ms < 10 ? "0" + ms : ms)
);
}
function snap() {
if (timeCounter) {
var li = document.createElement("li");
li.innerText = displayTimeCount();
lapsContainer.appendChild(li);
}
}
function resetSnaps() {
lapsContainer.innerHTML = "";
}
// Script to put lap into input box
var items = document.querySelectorAll("#list li");
for (var i = 0; i < items.length; i++) {
items[i].onclick = function () {
document.getElementById("inptSnap").value = this.innerHTML;
};
}
This is the CodePen Link
I would be very grateful for any pointers and advice, thanks
You can do somthing like that...
PS: I think that the ergonomics of your button is to be reviewed, I did a kind of revision.
const
btStartPause = document.querySelector('#container button:nth-of-type(1)')
, btStopClear = document.querySelector('#container button:nth-of-type(2)')
, btSnap = document.querySelector('#container button:nth-of-type(3)')
, snapList = document.querySelector('ol')
, inptSnap = document.querySelector('input#inptSnap')
, chrono = ((dZTime='#container time') =>
{
const
displZone = document.querySelector(dZTime)
, chronoZero = '00:00:00.000'
, one_Sec = 1000
//, one_Min = one_Sec * 60
//, one_Hrs = one_Min * 60
, n_Dgts = (n,t) => `${t}`.padStart(n,'0')
;
let startTime = null
, timeElapsed = 0
, pausedTime = 0
, reqRef = null
, reqPause = false
, stoped = false
;
displZone.textContent = chronoZero
function reqLoop(timeStamp) // timeStamp is float
{
startTime ??= timeStamp // Logical nullish assignment (??=)
if (stoped)
{
cancelAnimationFrame(reqRef)
return
}
if (reqPause)
{
pausedTime = (timeStamp - startTime) - timeElapsed;
}
else
{
timeElapsed = ((timeStamp - startTime) - pausedTime) | 0 // get integer part of float
let
Tms = timeElapsed % one_Sec
, tim = (timeElapsed - Tms) / one_Sec
, T_s = tim % 60
, T_m = 0
, T_h = 0
;
tim = (tim - T_s) / 60
T_m = tim % 60
T_h = (tim - T_m) / 60
displZone.textContent = `${n_Dgts(2,T_h)}:${n_Dgts(2,T_m)}:${n_Dgts(2,T_s)}.${n_Dgts(3,Tms)}`
}
requestAnimationFrame( reqLoop )
}
const jso =
{ dispSz: chronoZero.length
, getVal: ()=> displZone.textContent
, start() { reqRef = requestAnimationFrame(reqLoop) }
, pause(OnOff) { reqPause = OnOff }
, stop() { stoped = true }
, RaZ()
{
startTime = null
timeElapsed = 0
pausedTime = 0
reqRef = null
reqPause = false
stoped = false
displZone.textContent = chronoZero
}
}
Object.freeze(jso)
return jso
})()
;
btStartPause.onclick =_=>
{
if (btStartPause.classList.toggle('pause') )
{
btStopClear.disabled = false
if ( btStartPause.dataset.lib !== 'continue' )
{
btStartPause.dataset.lib = 'continue'
chrono.start()
}
else
chrono.pause(false)
}
else
{
btStopClear.disabled = true
btStopClear.classList.remove('clear')
chrono.pause(true)
}
}
btStopClear.onclick =_=>
{
if (btStopClear.classList.toggle('clear') )
{
btStartPause.disabled = true
btStartPause.dataset.lib = 'start'
btStartPause.classList.remove('pause')
chrono.stop()
}
else
{
btStartPause.disabled = false
btStopClear .disabled = true
chrono.RaZ()
}
}
btSnap.onclick =_=>
{
snapList
.appendChild( document.createElement('li'))
.innerHTML = chrono.getVal()
+ '<span title="delete"> ✖ </span>'
+ '<span title="copy"> ⎘ </span>'
}
snapList.onclick =({target}) =>
{
if (!target.matches('li > span'))
{
inptSnap.value = target.closest('li').textContent.substring(0, chrono.dispSz)
inptSnap.focus()
return
}
if (target.matches('span[title=delete]'))
{
target.closest('li').remove()
}
if (target.matches('span[title=copy]'))
{
let origin = target.closest('li')
copySomething ( origin.textContent.substring(0, chrono.dispSz), origin )
}
}
async function copySomething(toCopy, el )
{
try
{
await navigator.clipboard.writeText(toCopy);
el.classList.add('copyOK')
setTimeout(() => { el.classList.remove('copyOK')}, 1200);
}
catch (err)
{
el.classList.add('copyBad')
setTimeout(() => { el.classList.remove('copyBad')}, 1200);
console.error('Failed to copy :/', err);
}
}
body {
font-family : Arial, Helvetica, sans-serif;
font-size : 16px;
}
time {
display : block;
font-size : 1.4rem;
margin : .6rem 1rem;
letter-spacing : .2rem;
}
ol {
list-style : none;
font-size : 1.6rem;
padding : 0;
margin : 1.5rem;
width : 15rem;
list-style-type: decimal;
}
li {
border : 1px solid lightblue;
padding : .3rem .6rem;
position : relative;
cursor : pointer;
}
li::marker {
font-size : .9rem;
color : darkslategray;
}
li span {
float : right;
margin : 0 0 0 .3em;
font-size : 1.2rem;
color : darkslategray;
}
li span[title=delete]:hover {
color : crimson;
}
li span[title=copy]:hover {
background : white;
color : darkblue;
}
#container button {
min-width : 4.4rem;
text-transform : capitalize;
}
#container button:before {
content : attr(data-lib)
}
#container button.pause:before {
content : 'pause'
}
#container button.clear:before {
content : 'clear'
}
li:hover {
background : lightblue;
}
li.copyOK::after,
li.copyBad::after {
position : absolute;
display : block;
font-size : .8rem;
top : 1.2rem;
left : 11rem;
padding : .1rem .2rem;
}
li.copyOK::after {
content : 'copied';
background : lightgreen;
}
li.copyBad::after {
left : 1rem;
content : 'Failed to copy :/';
background : lightcoral;
}
<input type="text" id="inptSnap" >
<hr>
<div id="container">
<time datetime="00:00:00.000">00:00:00.000</time>
<button data-lib="start"><!-- start / continue / pause --></button>
<button data-lib="stop" disabled><!-- stop / clear --></button>
<button>snap</button>
</div>
<ol></ol>
for info :
Fastest way to cast a float to an int in javascript?
So I understand that you need a place value kind of thing.
var begin = document.getElementById("begin");
begin.addEventListener("click", start);
var end = document.getElementById("end");
end.addEventListener("click", stop);
var hold = document.getElementById("hold");
hold.addEventListener("click", pause);
var timeSnap = document.getElementById("timeSnap");
timeSnap.addEventListener("click", snap);
var timeSnap = document.getElementById("timeSnap");
timeSnap.addEventListener("click", pause);
var resetSnap = document.getElementById("resetSnap");
resetSnap.addEventListener("click", resetSnaps);
var ms = 0,
s = 0,
m = 0;
var timeCounter;
var displayEl = document.querySelector(".timeDisplay");
var lapsContainer = document.querySelector(".laps");
function start() {
if (!timeCounter) {
timeCounter = setInterval(run, 10);
}
}
function run() {
displayEl.textContent = displayTimeCount();
ms++;
if (ms == 100) {
ms = 0;
s++;
}
if (s == 60) {
s = 0;
m++;
}
}
function stop() {
stopTimer();
ms = 0;
s = 0;
m = 0;
displayEl.textContent = displayTimeCount();
}
function stopTimer() {
clearInterval(timeCounter);
timeCounter = false;
}
function pause() {
stopTimer();
}
function displayTimeCount() {
return (
(m < 10 ? "0" + m : m) +
":" +
(s < 10 ? "0" + s : s) +
":" +
(ms < 10 ? "0" + ms : ms)
);
}
function snap() {
if (timeCounter) {
var input = document.createElement("input");
input.value = displayTimeCount();
lapsContainer.appendChild(input);
}
}
function resetSnaps() {
lapsContainer.innerHTML = "";
}
// Script to put lap into input box
var items = document.querySelectorAll("#list li");
for (var i = 0; i < items.length; i++) {
items[i].onclick = function () {
document.getElementById("inptSnap").value = this.innerHTML;
};
}
.timeDisplay {
font-size: 32px;
}
ul li {
list-style: none;
font-size: 32px;
}
.container {
width: 400px;
margin: auto;
}
<div class="container">
<!-- Different App -->
<div class="timeDisplay">00:00:00</div>
<button id="begin">Start</button>
<button id="hold">Pause</button>
<button id="end">Stop</button>
<button id="timeSnap">Time Snap</button>
<button id="resetSnap">Reset Time Snap</button>
<ul id="list" class="laps">
</ul>
<div>
<input type="text" id="inptSnap" />
</div>
</div>
All rows always have same numbers, why? They should take random number to populate it. Also, how can I repair it? Once I saw answer here but now I cannot find it.
var mapSizex = 5;
var mapSizey = 6;
var mapArray = [];
$(function() {
console.log("ready!");
$('#map-draw').html(drawMap());
});
function mapGenerator() {
for (i = 0; i < mapSizex; i++) {
for (x = 0; x < mapSizey; x++) {
mapArray[i, x] = getRandom(1, 5);
}
}
}
function drawMap() {
mapGenerator();
var map = '';
tileID = 0;
for (i = 0; i < mapSizex; i++) {
map = map + '<br style="clear: both;">';
for (x = 0; x < mapSizey; x++) {
map = map + '<div class="tile tileID' + tileID + '">' + mapArray[i, x] + '</div>';
tileID++;
}
}
return map;
}
function getRandom(min, max) {
var x = Math.floor((Math.random() * max) + min);
return x;
}
.tile {
float: left;
height: 20px;
width: 20px;
border: 1px solid black;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main-container">
<div id="map-container">
<div id="map-draw"></div>
</div>
</div>
To post it I need to add some more content but all included information's should be enough to find what I mean.
here is a link to JSFIDDLE woking code
It should be mapArray[i][x] and I added mapArray[i]=[]; in the outer loop.
here is your fixed code:
var mapSizex=5;
var mapSizey=6;
var mapArray=[];
$(function() {
console.log( "ready!" );
$('#map-draw').html(drawMap());
});
function mapGenerator(){
for(i=0;i<mapSizex;i++){
mapArray[i]=[];
for(x=0;x<mapSizey;x++){
mapArray[i][x]= getRandom(1,5);
console.log(i,x,getRandom(1,5))
}
}
}
function drawMap(){
mapGenerator();
console.log(mapArray)
var map='';
tileID=0;
for(i=0;i<mapSizex;i++){
map=map+'<br style="clear: both;">';
for(x=0;x<mapSizey;x++){
map=map+'<div class="tile tileID'+tileID+'">'+mapArray[i][x]+'</div>';
tileID++;
}
}return map;
}
function getRandom(min,max) {
var x = Math.floor((Math.random() * max) + min);
return x;
}
I'm building a counter and have some issue with. I have a counter field where increment and decrement happen (by default it's 5 minutes). When 'start' button is pressed the final counter's digit should be set as the timer in the output field.
here is my solution:
;(function(){
var output = document.querySelector('#output'),
btn = document.querySelector('button'),
min = 5,
sec = min * 60,
timer;
setCount(min);
function setCount(n){
var c = document.querySelector('#counter'),
increment = c.children[1].children[0],
decrement = c.children[1].children[2],
num = c.children[1].children[1];
increment.onclick = function(){
if(n >= 1) {num.textContent = ++n;}
};
decrement.onclick = function(){
if(n > 1) {num.textContent = --n;}
};
num.textContent = n;
}
function setTimer(){
var currentMin = Math.round((sec - 30) / 60),
currentSec = sec % 60;
if(currentMin >= 0 ) {currentMin = '0' + currentMin;}
if(currentSec <= 9 ) {currentSec = '0' + currentSec;}
if(sec !== 0){sec--;}
timer = setTimeout(setTimer,10); // 10 is for the speedy
output.textContent = currentMin + ':' + currentSec;
}
btn.addEventListener('click', setTimer, false);
})();
here is the link : JS Bin
TL;DR
if(n >= 1) {num.textContent = ++n; sec = n * 60;} // Line 15
...
if(n > 1) {num.textContent = --n; sec = n * 60; } // Line 19
Your timer is deriving it's start min value from the seconds, which is always equal to 5 * 60. You need to update the seconds every time that the + or - is clicked.
(function() {
var output = document.querySelector('#output');
var btn = document.querySelector('button');
var min = 5;
var sec = min * 60;
var timer;
var counter = document.querySelector('#counter ul');
var increment = counter.children[0];
var decrement = counter.children[2];
var number = counter.children[1];
number.textContent = min;
increment.onclick = function() {
min++;
number.textContent = min;
sec = min * 60;
};
decrement.onclick = function() {
min--;
if (min < 1) {
min = 1;
}
sec = min * 60;
number.textContent = min;
};
function setTimer() {
var currentMin = Math.round((sec - 30) / 60),
currentSec = sec % 60;
if (currentMin == 0 && currentSec == 0) {
output.textContent = '00:00';
return;
} else {
timer = setTimeout(setTimer, 10);
}
if (currentMin <= 9) {
currentMin = '0' + currentMin;
}
if (currentSec <= 0) {
currentSec = '0' + currentSec;
}
if (sec !== 0) {
sec--;
}
output.textContent = currentMin + ':' + currentSec;
console.log('currentMin: ' + currentMin);
}
btn.addEventListener('click', setTimer, false);
})();
#wrapper {
width: 300px;
border: 1px solid #f00;
text-align: center;
}
#output {
height: 40px;
line-height: 40px;
border-bottom: 1px solid #f00;
}
h4 {
margin: 10px 0;
}
ul {
margin: 0;
padding: 0;
}
li {
list-style: none;
width: 40px;
height: 40px;
line-height: 40px;
display: inline-block;
border: 1px solid #f00;
}
li:nth-child(odd) {
cursor: pointer;
}
button {
padding: 5px 15px;
margin: 10px 0;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="wrapper">
<div id="output"></div>
<div id="counter">
<h4>counter</h4>
<ul>
<li>+</li>
<li></li>
<li>-</li>
</ul>
</div>
<button id="start">start</button>
</div>
</body>
</html>
I have a countdown I am trying to have a visual display with css circles of the count down. But I cant figure out what to do to take away one circle at a time. My code duplicates the number of circles each loop. I know why, but what can I now do to get it to take one away each time?
JS Fiddle: http://jsfiddle.net/L0o9jmw9/
JS:
var sec = 5
function setClock() {
var totalSec = sec--;
var s = parseInt(totalSec % 60, 10);
var result = s + " seconds to go!";
document.getElementById('timeRemaining').innerHTML = result;
if(totalSec === 0){
document.getElementById('timeRemaining').innerHTML = 'time out';
}else{
for(var i = 0; i < s; i++){
//console.log(i);
$('.cont-s').prepend('<div class="cir-s"></div>');
}
setTimeout(setClock, 1000);
}
}
setClock();
HTML:
<div id="timeRemaining"></div>
<div class="cont-s"></div>
CSS:
.cir-s{
width: 20px;
height: 20px;
background: #802A2A;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
float:left;
}
Simply empty the HTML before each iteration:
function setClock() {
$('.cont-s').empty(); // empty the circles div
var totalSec = sec--;
var s = parseInt(totalSec % 60, 10);
var result = s + " seconds to go!";
document.getElementById('timeRemaining').innerHTML = result;
if(totalSec === 0){
document.getElementById('timeRemaining').innerHTML = 'time out';
} else {
for(var i = 0; i < s; i++){
$('.cont-s').prepend('<div class="cir-s"></div>');
}
setTimeout(setClock, 1000);
}
}
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>