How to add timer until tomorrow in HTML - javascript

I am beginner in HTML and I am trying to put a timer in my HTML university project daily word game that shows time left until the next day and word. I found a W3Schools tutorial for a timer but it does not work for me because it is until constant date.
My code looks like this:
<!DOCTYPE html>
<html>
<head>
<link rel="icon" href="images/tabIcon.ico">
<title>Daily WordGame</title>
<style>
h1 {
font-family: Tahoma, sans-serif;
text-align: center;
}
p {
font-size: large;
text-align: center;
}
</style>
</head>
<body>
<h1>Welcome to your daily source of educational fun</h1>
<hr>
<p style="font-size: large;">Everyday you have a chance of guessing a different word.
</p>
Go to about
<p>this is a second text</p>
<ul>
<li>Boats</li>
<li>Cars</li>
<ul>
<li>Buggati</li>
<table>
<tr>
<td>Price</td>
<td>Top speed</td>
<td>0-100</td>
<td>Horse Power</td>
</tr>
<tr>
<td>3.300.000$</td>
<td>420km/h</td>
<td>2.2s</td>
<td>1480</td>
</tr>
</table>
<img src="images/car.jpg" style="width: 500px;height:300px;">
</ul>
<li>Trucks</li>
</ul>
</body>
<html>

Add a span or any text element with an id of timer
<span id="timer">Time until next word: </span>
And add JavaScript code to get the countdown
<script>
var now = new Date();
// If you want another time, set it here with javascrip Date API
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
var tomorrow = new Date().setDate(now.getDate() + 1);
var timer = document.getElementById("timer");
// Update the count down every 1 second
setInterval(() => {
// Fill in with the time until tomorrow
var time = new Date(tomorrow - now);
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
// Format the time to add a leading 0 if less than 10
function fillZero(n) {
if (n < 10) {
return "0" + n;
} else return n.toString();
}
timer.innerText = "Time until next word: " + "0d " + fillZero(hours) + "h " + fillZero(minutes) + "m " + fillZero(seconds) + "s";
}, 1000);
</script>
So the modified code with your HTML is
<!DOCTYPE html>
<html>
<head>
<link rel="icon" href="images/tabIcon.ico">
<title>Daily WordGame</title>
<style>
h1 {
font-family: Tahoma, sans-serif;
text-align: center;
}
p {
font-size: large;
text-align: center;
}
</style>
</head>
<body>
<h1>Welcome to your daily source of educational fun</h1>
<hr>
<p style="font-size: large;">Everyday you have a chance of guessing a different word.
</p>
Go to about
<p>this is a second text</p>
<span id="timer">Time until next word: </span>
<ul>
<li>Boats</li>
<li>Cars</li>
<ul>
<li>Buggati</li>
<table>
<tr>
<td>Price</td>
<td>Top speed</td>
<td>0-100</td>
<td>Horse Power</td>
</tr>
<tr>
<td>3.300.000$</td>
<td>420km/h</td>
<td>2.2s</td>
<td>1480</td>
</tr>
</table>
<img src="images/car.jpg" style="width: 500px;height:300px;">
</ul>
<li>Trucks</li>
</ul>
<script>
var now = new Date();
// If you want another time, set it here with javascrip Date API
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
var tomorrow = new Date().setDate(now.getDate() + 1);
var timer = document.getElementById("timer");
// Update the count down every 1 second
setInterval(() => {
// Fill in with the time until tomorrow
var time = new Date(tomorrow - now);
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
// Format the time to add a leading 0 if less than 10
function fillZero(n) {
if (n < 10) {
return "0" + n;
} else return n.toString();
}
timer.innerText = "Time until next word: " + "0d " + fillZero(hours) + "h " + fillZero(minutes) + "m " + fillZero(seconds) + "s";
}, 1000);
</script>
</body>
<html>

Related

JavaScript problem adding a class to HTML [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Good day
I am starting to practice with JavaScript and recently I mounted a simple digital clock using the local time of my pc, I have proposed to add something else to it, to show me the current day in which we are, I want to achieve this with a single tag <p> where it contains the days: Mon - Tue - Wed - Thu - Fri - Sat - Sun, The idea is to apply a different style to the current day using a <span> tag, I do not know if it is the correct way to do it or if there is a more efficient way that consumes less resources and I would like you to help me with this to improve my code .
My current problem boils down to somehow that I am misusing the Element.classList.add (" class "); and I can't update the class of my element.
I attach my code:
"use strict";
const hour = document.getElementById("hour");
const date = document.getElementById("date");
const days = document.getElementById("day");
let daysString = '<span id="mon"> Mon </span> - <span id="tue"> Tue </span> - <span id="wed"> Wed </span> - ' +
'<span id="thu">Thu </span> - <span id="fri"> Fri </span> - <span id="sat"> Sat </span> - <span id="sun"> Sun </span>';
const nameMonths = ["January","February","March","April","May","June","July",
"August","September","October","November","December"];
days.innerHTML = daysString;
const getTime = ()=>{
const local = new Date();
let day = local.getDate(),
month = local.getMonth(),
year = local.getFullYear();
let getTime = local.toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric', second: 'numeric',
hour12: true });
let time = getTime.slice(0, -2);
let moment = getTime.slice(-2);
hour.innerHTML = `${time} <span class="ampm">${moment[0]}.${moment[1]}.</span>`;
date.innerHTML = `${day} / ${nameMonths[month]} / ${year}`;
// ------------------------------------------------------------------------------------------------------------
let d = local.getDay();
let finalDays = daysString;
days.innerHTML = finalDays;
let currentDay;
switch(d){
case 0:
currentDay = document.getElementById("sun");
currentDay.classList.add("active-day");
break;
case 1:
currentDay = document.getElementById("mon");
currentDay.classList.add("active-day");
break;
case 2:
currentDay = document.getElementById("tue");
currentDay.classList.add("active-day");
break;
case 3:
currentDay = document.getElementById("wed");
currentDay.classList.add("active-day");
break;
case 4:
currentDay = document.getElementById("thu");
currentDay.classList.add("active-day");
break;
case 5:
currentDay = document.getElementById("fri");
currentDay.classList.add("active-day");
break;
case 6:
currentDay = document.getElementById("sat");
currentDay.classList.add("active-day");
break;
default:
finalDays = daysString;
}
days.innerHTML = finalDays;
}
getTime();
setInterval(getTime,1000);
* {
margin: 0;
padding: 0;
}
body{
background: url(background2.jpg) no-repeat center center fixed;
background-size: cover;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
font-family: 'lato';
}
.container-clock{
text-align: center;
color: #fff;
}
.container-clock h1{
font-size: 12rem;
font-weight: 400;
text-shadow: 0 0 20px #409CFA;
}
.dates{
font-size: 2.5rem;
font-family: Verdana, Geneva, Tahoma, sans-serif;
text-shadow: 0 0 10px #409CFA;
}
.days{
font-size: 1.5rem;
font-family: Verdana, Geneva, Tahoma, sans-serif;
color: rgb(155, 155, 155);
text-shadow: 0 0 8px #409CFA;
}
.active-day{
color: #fff;
text-shadow: 0 0 10px #409CFA;
font-size: 2rem;
}
.ampm{
font-size: 5rem;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Digital clock</title>
</head>
<body ondragstart="return false" onselectstart="return false" oncontextmenu="return false">
<div class="container-clock">
<h1 id="hour">00:00:00</h1>
<p id="date" class="dates">date</p>
<br><br>
<p id="day" class="days">day-day-day-day-day-day-day</p>
</div>
<script src="clock.js"></script>
</body>
</html>
I can not get the desired effect since I can not add the desired class to the elements, I would appreciate whoever tells me that I am doing wrong.
In the same way, I would appreciate any advice and / or ideas on how to improve this code, for example, I understand that it would be better to use if / else thanswitch ()since it consumes less resources.
I have also realized that I am not deleting the active day class when the day ends at 23:59, in the same way at the moment there is no class to replace or delete until I solve my problem.
Thank you very much in advance to anyone who can help me!
there is a problem in line 31:
fecha.innerHTML = `${day} / ${nameMonths[month]} / ${year}`;
you didn't defined the varible fecha
the main problem you showed here happening because you copy the 'innerHTML' of day, then change things inside day, and paste back the innerHTML you copied.
the solution is just removing the lines:
let finalDays = daysString;
days.innerHTML = finalDays;
and the line at the end:
days.innerHTML = finalDays;
a thing I noticed is that you are changing the html of days at the beginning of the java script, you don't need to do that if you can just write this in the html
i wrote a simplification for the switch case you wrote:
let d = local.getDay();
let currentDay = days.children[(d + 6) % 7];
let lastDay = days.children[(d + 5) % 7];
currentDay.className = "active-day";
lastDay.className = "inactive-day";
(i added 6 instead of removing 1 because (0 - 1) % 7 is -1 and not 6)
instead of
const getTime = ()=>{
you can just write
function getTime() {
(its more standard)
the final code:
"use strict";
const hour = document.getElementById("hour");
const date = document.getElementById("date");
const days = document.getElementById("day");
const nameMonths = ["January","February","March","April","May","June","July",
"August","September","October","November","December"];
function getTime() {
const local = new Date();
let day = local.getDate(),
month = local.getMonth(),
year = local.getFullYear();
let getTime = local.toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric', second: 'numeric',
hour12: true });
let time = getTime.slice(0, -2);
let moment = getTime.slice(-2);
hour.innerHTML = `${time} <span class="ampm">${moment[0]}.${moment[1]}.</span>`;
//fecha.innerHTML = `${day} / ${nameMonths[month]} / ${year}`;
// ------------------------------------------------------------------------------------------------------------
let d = local.getDay();
let currentDay = days.children[(d + 6) % 7];
let lastDay = days.children[(d + 5) % 7];
currentDay.className = "active-day";
lastDay.className = "inactive-day";
}
getTime();
setInterval(getTime,1000);
* {
margin: 0;
padding: 0;
}
body{
background: url(background2.jpg) no-repeat center center fixed;
background-size: cover;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
font-family: 'lato';
}
.container-clock{
text-align: center;
color: #fff;
}
.container-clock h1{
font-size: 12rem;
font-weight: 400;
text-shadow: 0 0 20px #409CFA;
}
.active-day {
color: aqua;
}
.inactive-day {
color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Digital clock</title>
</head>
<body ondragstart="return false" onselectstart="return false" oncontextmenu="return false">
<div class="container-clock">
<h1 id="hour">00:00:00</h1>
<p id="date" class="dates">date</p>
<br><br>
<p id="day" class="days">
<span class="inactive-day">Mon</span>-
<span class="inactive-day">Tue</span>-
<span class="inactive-day">Wed</span>-
<span class="inactive-day">Thu</span>-
<span class="inactive-day">Fri</span>-
<span class="inactive-day">Sat</span>-
<span class="inactive-day">Sun</span>
</p>
</div>
<script src="clock.js"></script>
</body>
</html>
btw, you don't need to worry about consuming less resources because javascript is not for making thing that need lot of resources
(sorry if my english is bad, its not my native language)

Can't get the numeric value from HTML using parseInt or Number in my js function

So I'm trying to complete this simple html page for a friend's project, the goal is to get 2 user entries, minutes and seconds, that will be compared to the data already in the table and if the minutes and seconds entered are greater than one of the time in the table, it will be replaced by the entry.
I've never worked with js except to make some simple prompt or alert so I don't know what I'm supposed to do.
Here is the html, js and css :
function timeEntry() {
var min1 = Number(document.getElementById('firstTimeMin'));
var sec1 = Number(document.getElementById('firstTimeSec'));
var min2 = Number(document.getElementById('secondTimeMin'));
var sec2 = Number(document.getElementById('secondTimeSec'));
var min3 = Number(document.getElementById('thirdTimeMin'));
var sec3 = Number(document.getElementById('thirdTimeSec'));
var entryMin = Number(prompt('What is the time in minutes ?'));
var newTimeMin = entryMin;
var entrySec = Number(prompt('What is the time in seconds'));
var newTimeSec = entrySec;
for (var i = 0; i < 3; i++) {
if (entryMin > min1 && entrySec > sec1) {
document.getElementById('firstTimeMin').innerHTML = newTimeMin;
document.getElementById('firstTimeSec').innerHTML = newTimeSec;
break;
} else if (entryMin > min2 && entrySec > sec2) {
document.getElementById('secondTimeMin').innerHTML = newTimeMin;
document.getElementById('secondTimeSec').innerHTML = newTimeSec;
break;
} else if (entryMin > min3 && entrySec > sec3) {
document.getElementById('thirdTimeMin').innerHTML = newTimeMin;
document.getElementById('thirdTimeSec').innerHTML = newTimeSec;
break;
}
};
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
height: 100%;
}
section {
width: 100%;
height: 100%;
}
table,
td {
width: 40%;
text-align: center;
border: 1px solid black;
border-collapse: collapse;
}
button {
cursor: pointer;
font-weight: 700;
}
<!DOCTYPE html>
<html>
<head>
<title>Table of best times</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="javascript/besttime.js"></script>
</head>
<body>
<section>
<table>
<tbody>
<caption>The best times</caption>
<tr>
<td id="firstTimeMin">1</td>
<td id="firstTimeSec">2</td>
</tr>
<tr>
<td id="secondTimeMin">3</td>
<td id="secondTimeSec">4</td>
</tr>
<tr>
<td id="thirdTimeMin">5</td>
<td id="thirdTimeSec">6</td>
</tr>
</tbody>
</table>
<button onclick="timeEntry()">
Enter a new time
</button>
</section>
</body>
</html>
My idea was to simply get the data already in the table using Number or parseInt to get the number value, but either way from the test I've been doing, when I try to get the element from html, it tells me that I get a number type but when I try to use it in an operation it returns NaN. Maybe I'm just stupid, but I've been reading and looking for a day for a way to get the data from the cells as numbers, but aside from Number or parseInt or using a form, I haven't seen a way to do this and it feels like the more I search the less I understand why it doesn't work.
Any help or clue on how to get this done, even it means start back from scratch would be really appreciated.
document.getElementById('firstTimeMin') only get the DOM Element, you should do document.getElementById('firstTimeMin').innerHTML to get the content of the HTML so you'll be able to get the number using parseInt() or Number.
Do the same with every elements.

Appending timer into <div>

Functionality:
A timer will start counting from 0 seconds and value will increment every 1 second. The timer will continue to increment till it reaches 59 mins 59secs before the timer will stop.
What has been done:
I have set 2 different <div> that will dynamically display the timer value as it is increasing. 1st <div> is for the minute value while the 2nd <div> is for the second value.
While the timer increment is done a setinterval method of 1 second
Issue:
I have tried to append the value of timer to one of the <div> but realise that the minute value of the timer will not be able to be appended to the 1st <div> and the value will only be displayed in the 2nd <div>
Hence, I would like to ask for assistance on how to splice the value of the system timer such that the minute value can be appended and can be displayed in the 1st <div> when the second value can be appended and can be displayed in the 2nd <div>
Code:
var GameTimer = 0;
$("#Game_Elements").fadeIn({
queue: false,
complete: function() {
//Start Game Timer
var SetGameTimer = setInterval(function() {
GameTimer++;
//append timer to timer game elements
$("#Game_Minute_timer").html(GameTimer);
$("#Game_Second_timer").html(GameTimer);
//Check on time, if more than 1hr, automatically navigate to last game page
}, 1000);
}
});
<div id="Game_Elements" style="position:absolute; z-index:7; top:0px; left:0px; width: 1920px; heigth: 1000px; margin:auto;">
<table id="Game_Timer_Element">
<tr>
<td>
<div id="Game_Minute_timer" style="z-index:50; position:absolute; top:609px; left:900px; font-size:90px; font-family:'GothicBold'; width:1080; color:#fff;">
<font face="GothicBold"></font>
</div>
</td>
<td>
<div id="Game_Second_timer" style="z-index:50; position:absolute; top:609px; left:900px; font-size:90px; font-family:'GothicBold'; width:1080; color:#fff;">
<font face="GothicBold"></font>
</div>
</td>
</tr>
</table>
</div>
I think your best bet would be to put the time in one div and use Modulus/Math.floor to do your Minute:Second timer.
Like this:
$("#Game_timer").html(Math.floor(GameTimer / 60) + ":" + GameTimer % 60);
If you want to keep them in separate div's go ahead and stick with the same layout you had, and use
Math.Floor(GameTimer / 60)
for minutes, and
Gametimer % 60
for seconds.
You have only seconds, so you have to split them to minutes and seconds. For example:
var GameTimer = 0;
$("#Game_Elements").fadeIn({
queue: false,
complete: function() {
//Start Game Timer
var SetGameTimer = setInterval(function() {
GameTimer++;
var minutes = ('0' + Math.floor(GameTimer/ 60)).slice(-2);
var seconds = ('0' + (GameTimer - minutes * 60)).slice(-2);
if(minutes < 60){
//append timer to timer game elements
$("#Game_Minute_timer").html(minutes+" : ");
$("#Game_Second_timer").html(seconds);
}
//Check on time, if more than 1hr, automatically navigate to last game page
}, 1000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Game_Elements" style="">
<table id="Game_Timer_Element">
<tr>
<td>
<div id="Game_Minute_timer" style="">
<font face="GothicBold"></font>
</div>
</td>
<td>
<div id="Game_Second_timer" style="">
<font face="GothicBold"></font>
</div>
</td>
</tr>
</table>
</div>

Fill a circle over time

I am doing a project where I created a countdown timer using JavaScript. It features stop-, start-, and reset buttons.
I want to create a fill effect animation starting from the bottom, based on the countdown timer. I want the fill effect to fill a certain percentage of the circle so that when the countdown reaches 0, the whole circle will be filled.
I want to use vanilla JavaScript. No jQuery or SVG.
Here is my code so far for the basic timer starting with HTML, then CSS and my Javascript code.
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<h1>Pomodoro Clock</h1>
<div class="container">
<div class="row">
<h3>Session Length</h3>
<div class="row button1">
<button type="button" onclick="decreaseTime()">-</button>
<span id="SessionLength">25</span>
<button type="button" onclick="increaseTime()">+</button>
</div>
</div>
<!--My Start/Stop/Reset buttons-->
<div class="row">
<div class="myButtons">
<button type="button" onclick="startTime()">Start</button>
<button type="button" onclick="stopTime()">Stop</button>
<button type="button" onclick="resetTime()">Reset</button>
</div>
</div>
<!--My Circle-->
<div class="row">
<div class="circleDraw">
<h2 class="text-center">Session</h2>
<h1 id="output">25:00</h1>
</div>
</div>
</div>
h1{
text-align: center;
}
h3{
text-align: right;
padding-right: 30%;
}
.myButtons{
text-align: center;
padding-top: 10%;
}
.circleDraw{
border-radius: 50%;
border: 2px solid;
width: 300px;
height: 300px;
margin: 50px auto;
}
.text-center{
text-align: center;
padding: 30px;
}
.txt-center{
text-align: center;
}
.button1{
text-align: right;
padding-right: 35%
}
var time = 1500;
var running = 0;
var myStopID;
var startTime = function(){
running = 1;
if(running == 1){
timer();
}
}
var stopTime = function(){
clearTimeout(myStopID);
running = 0;
}
var resetTime = function(){
if(running == 0){
time = 1500;
}
var min = Math.floor(time / 60);
var sec = time % 60;
min = min < 10 ? "0" + min : min;
sec = sec < 10 ? "0" + sec : sec;
document.getElementById('output').innerHTML= min;
document.getElementById('SessionLength').innerHTML= min;
}
var timer = function(){
if(running == 1){
myStopID = setTimeout(function(){
time--;
var min = Math.floor(time / 60);
var sec = time % 60;
min = min < 10 ? "0" + min : min;
sec = sec < 10 ? "0" + sec : sec;
document.getElementById("output").innerHTML= min + ":" + sec;
timer();
}, 1000);
}
}
function decreaseTime(){
if(time <= 0){
return 0;
}
time = time - 60;
var min = Math.floor(time/60);
document.getElementById('SessionLength').innerHTML= min;
document.getElementById('output').innerHTML= min;
}
function increaseTime(){
if(time >= 5940){
return 5940;
}
time = time + 60;
var min = Math.floor(time/60);
document.getElementById('SessionLength').innerHTML= min;
document.getElementById('output').innerHTML= min;
}
What you have done so far looks good. I'd look at using the canvas element and the arc() method on that to draw the circle and partial fill.
More info here...
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes
And basic Canvas and SVG example for drawing a circle in this answer...
https://stackoverflow.com/a/6936351/4322803

javascript to replace button text with images...trigger button with external event

I found this stopwatch javascript, complete with "Start", "Stop" and "Reset" buttons. The functionality of this script is great, but I would like to spruce it up a bit. I've managed to style the button background with CSS border-image, but I want to use javascript to replace the "Start", "Stop" and "Reset" text with icons.
I would also like to make the timer start when the user clicks on another area. For example, I may use this to track how long a user takes to solve a puzzle...so it would be great if the "Start" button could be activated upon the user's FIRST event recorded on the puzzle. I though about making an event listener for any click, but I'm afraid that may cause the button to toggle Start/Stop on each event.
Lastly, it would be nice if the "Stop" button triggered a hidden div with a message screen that shows up on top of the puzzle while the game is paused. Below is a snippet of my code
JAVASCRIPT
var sec = 0;
var min = 0;
var hour = 0;
function stopwatch(text) {
sec++;
if (sec == 60) {
sec = 0;
= min + 1; }
else {
min = min; }
if (min == 60) {
min = 0;
hour += 1; }
if (sec<=9) { sec = "0" + sec; }
document.clock.stwa.value = ((hour<=9) ? "0"+hour : hour) + " : " + ((min<=9) ? "0" + min : min) + " : " + sec;
if (text == "Start") { document.clock.theButton.value = "Stop";}
if (text == "Stop") { document.clock.theButton.value = "Start"; }
if (document.clock.theButton.value == "Start") {
window.clearTimeout(SD);
alert("Timer is Paused...Resume?");
return true; }
SD=window.setTimeout("stopwatch();", 1000);
}
function resetIt() {
sec = -1;
min = 0;
hour = 0;
if (document.clock.theButton.value == "Stop") {
document.clock.theButton.value = "Start"; }
window.clearTimeout(SD);
}
CSS
.button {
border-width:0 5px; -webkit-border-image:url(../images/toolButton-791569.png) 0 5 0 5; padding:7px 0; font: bold 12px Arial,sans-serif; color:#fff; width:auto; margin:5px 10px 0 0; width:auto; height: 25px; text-align:center; cursor:pointer;
}
HTML
<div id="timer">
<form name="clock">
<input type="text" size="14" name="stwa" value="00 : 00 : 00" style="text-align:center; position: relative; top: 0px; background: #ccc; font-weight: bold; font-size: 14px;" />
<br/><input type="button" class="button" name="theButton" onClick="stopwatch(this.value);" value="Start" />
<input type="button" class="button" value="Reset" onClick="resetIt();reset();" />
</form></div>
I'm sure the brilliant programmers in this community might find this question to be trivial, but please forgive me. I am a novice programmer and this challenge is causing me many sleepless nights. Please help...
Thanks,
Carlos
Here you go http://jsfiddle.net/mplungjan/C4wjV/
I did not do the pause button
<style type="text/css">
img { height:50px }
#stwa {text-align:center; position: relative; top: 0px; background: #ccc; font-weight: bold; font-size: 14px;}
</style>
<script type="text/javascript">
var buttons = {
Start:"http://morethanvoice.net/m1/img/play.gif",
Stop:"http://morethanvoice.net/m1/img/pause.gif"
}
var sec = 0,min = 0,hour = 0,SD;
function stopwatch(text) {
sec++;
if (sec === 60) {
sec = 0;
min += 1;
}
if (min === 60) {
min = 0;
hour += 1;
}
document.clock.stwa.value = ((hour<10) ? "0"+hour : hour) + " : " +
((min<10) ? "0" + min : min) + " : " +
((sec<10)? "0" + sec:sec);
if (text) { // i.e. we are clicked
if (text==="Stop") window.clearTimeout(SD);
text = (text==="Start")?"Stop":"Start";
document.getElementById('stopstart').title=text;
document.getElementById('stopstarticon').src=buttons[text];
}
if (!text || text === "Stop") SD=window.setTimeout(function() {stopwatch()}, 1000);
return false;
}
function resetIt() {
sec = -1;
min = 0;
hour = 0;
document.getElementById('stopstart').title = "Start"
document.getElementById('stopstarticon').src=buttons["Start"];
window.clearTimeout(SD);
document.clock.stwa.value=document.clock.stwa.defaultValue;
return false;
}
</script>
<form name="clock"><input type="text" size="14" id="stwa" name="stwa" value="00 : 00 : 00" />
</form><br/>
<a href="#" id="stopstart" title="Start"
onClick="return stopwatch(this.title)"><img id="stopstarticon" src="http://morethanvoice.net/m1/img/play.gif" border="0" /></a>
<img src="http://morethanvoice.net/m1/img/rewind.gif" border="0" />

Categories