I am using bootstrap to style my button in HTML file by:
<button type="button" class="btn btn-primary">Start</button>
And I want to access the class in js file by
var buttonStart = document.getElementsByClassName('btn btn-primary');
And I got the error in the console. Is there any problem with my code?
VM131:1 Uncaught ReferenceError: buttonStart is not defined at <anonymous>:1:1
<p><span id="seconds">00</span>:<span id="tens">00</span></p>
<button type="button" class="btn btn-primary">Start</button>
<button type="button" class="btn btn-secondary">Stop</button>
<button type="button" class="btn btn-secondary">Reset</button>
window.onload = function(){
var seconds = 00;
var tens = 00;
var appendTens = document.getElementById("tens");
var appendSeconds = document.getElementById("seconds");
var buttonStart = document.getElementsByClassName('btn btn-primary');
var buttonStop = document.getElementsByClassName("btn btn-secondary");
var buttonReset = document.getElementsByClassName("btn btn-secondary");
var interval;
buttonStart.onclick = function(){
clearInterval(interval);
interval = setInterval(startTimer, 10);
}
buttonStop.onclick = function() {
clearInterval(interval);
}
buttonReset.onclick = function() {
clearInterval(interval);
tens = "00";
seconds = "00";
appendTens.innerHTML = tens;
appendSeconds.innerHTML = seconds;
}
function startTimer () {
tens++;
if(tens < 9){
appendTens.innerHTML = "0" + tens;
}
if (tens > 9){
appendTens.innerHTML = tens;
}
if (tens > 99) {
console.log("seconds");
seconds++;
appendSeconds.innerHTML = "0" + seconds;
tens = 0;
appendTens.innerHTML = "0" + 0;
}
if (seconds > 9){
appendSeconds.innerHTML = seconds;
}
}
}
The main issue is that you're capturing the <button> elements using getElementsByClassName. This method returns a HTML Collection which behaves like an array (technically an array like object). So, to fix this you would need to reference the first element of that collection:
var buttonStart = document.getElementsByClassName('btn btn-primary')[0]
Working example below:
window.onload = function() {
var seconds = 00;
var tens = 00;
var appendTens = document.getElementById("tens");
var appendSeconds = document.getElementById("seconds");
var buttonStart = document.getElementsByClassName('btn btn-primary')[0];
var buttonStop = document.getElementsByClassName("btn btn-secondary")[0];
var buttonReset = document.getElementsByClassName("btn btn-tertiary")[0];
var interval;
buttonStart.onclick = function() {
clearInterval(interval);
interval = setInterval(startTimer, 10);
}
buttonStop.onclick = function() {
clearInterval(interval);
}
buttonReset.onclick = function() {
clearInterval(interval);
tens = "00";
seconds = "00";
appendTens.innerHTML = tens;
appendSeconds.innerHTML = seconds;
}
function startTimer() {
tens++;
if (tens < 9) {
appendTens.innerHTML = "0" + tens;
}
if (tens > 9) {
appendTens.innerHTML = tens;
}
if (tens > 99) {
console.log("seconds");
seconds++;
appendSeconds.innerHTML = "0" + seconds;
tens = 0;
appendTens.innerHTML = "0" + 0;
}
if (seconds > 9) {
appendSeconds.innerHTML = seconds;
}
}
}
<p><span id="seconds">00</span>:<span id="tens">00</span></p>
<button type="button" class="btn btn-primary">Start</button>
<button type="button" class="btn btn-secondary">Stop</button>
<button type="button" class="btn btn-tertiary">Reset</button>
It's probably a better idea to use an ID along with getElementById or if you want to keep using those classes you can use querySelector which will return the first element that matches that specific class.
Note: I modified the third class to be btn-tertiary so the example could work.
you need to add 3 even listeners and define your functions correctly, the code is fine.
window.onload = function(){
var seconds = 00;
var tens = 00;
var appendTens = document.getElementById("tens");
var appendSeconds = document.getElementById("seconds");
var buttonStart = document.getElementsByClassName('btn btn-primary')[0];
var buttonStop = document.getElementsByClassName("btn btn-secondary")[0];
var buttonReset = document.getElementsByClassName("btn btn-secondary")[1];
var interval;
buttonStart.addEventListener("click", start);
function start() {
clearInterval(interval);
interval = setInterval(startTimer, 10);
}
buttonStop.addEventListener("click", stop);
function stop() {
clearInterval(interval);
}
buttonReset.addEventListener("click", restart);
function restart() {
clearInterval(interval);
tens = "00";
seconds = "00";
appendTens.innerHTML = tens;
appendSeconds.innerHTML = seconds;
}
function startTimer () {
tens++;
if(tens < 9){
appendTens.innerHTML = "0" + tens;
}
if (tens > 9){
appendTens.innerHTML = tens;
}
if (tens > 99) {
console.log("seconds");
seconds++;
appendSeconds.innerHTML = "0" + seconds;
tens = 0;
appendTens.innerHTML = "0" + 0;
}
if (seconds > 9){
appendSeconds.innerHTML = seconds;
}
}
}
<p><span id="seconds">00</span>:<span id="tens">00</span></p>
<button type="button" class="btn btn-primary">Start</button>
<button type="button" class="btn btn-secondary">Stop</button>
<button type="button" class="btn btn-secondary">Reset</button>
Related
I made a simple clock and used a button to switch to a stopwatch. Since I couldn't figure out a better solution I duplicated the container, asigned a function that toggles display on/off on the containers to swap between the clock and stopwatch so that it remains in the same position. I don't understand why my stopwatch is not incrementing and what I should do to solve this problem. Any help would be appreciated. Here's my code:
<div id="container">
<div id="clock">
<span id="back">88:88:88</span>
<span id="front">00:00:00</span>
<div class="buttons">
<button id="button-left" onclick="myFunction()"><i class="fas fa-stopwatch"></i></button>
<button id="button-stop"><i class="fa-solid fa-stop"></i></button>
<button id="button-play" ><i class="fa-solid fa-play"></i></button>
<button id="button-right"><i class="fa-solid fa-delete-left"></i></button>
</div>
</div>
</div>
<div id="container-2">
<div id="clock-2">
<span id="back-2">88:88:88</span>
<span id="front-2">00:00:00</span>
<div class="buttons-2">
<button id="button-left-2" onclick="myFunction()"><i class="fas fa-stopwatch"></i></button>
<button id="button-stop-2" onclick="stopSW()"><i class="fa-solid fa-stop"></i></button>
<button id="button-play-2" onclick="startSW()"><i class="fa-solid fa-play"></i></button>
<button id="button-right-2" onclick="reset()"><i class="fa-solid fa-delete-left"></i></button>
</div>
</div>
</div>
function myFunction() {
var x = document.getElementById("container-2");
let y = document.getElementById("container");
if (x.style.display === "none") {
x.style.display = "block";
y.style.display = "none";
} else {
x.style.display = "none";
y.style.display = "block";
}
}
function startSW() {
clearInterval(stopwatch);
start = setInterval(stopwatch, 1000);
}
function stopSW() {
clearInterval(start);
}
function reset(){
clearInterval(stopwatch);
document.getElementById("front-2").innerHTML = "00:00:00";
}
function stopwatch() {
let hours = 0;
let minutes = 0;
let seconds = 0;
let displayHours = 0;
let displayMinutes = 0;
let displaySeconds = 0;
seconds++;
if(seconds == 60){
seconds = 0;
minutes++;
if(minutes == 60) {
minutes = 0;
hours++;
}
}
if (seconds < 10){
displaySeconds = "0" + seconds;
} else {
displaySeconds = seconds;
}
if (minutes < 10){
displayMinutes = "0" + minutes;
} else {
displayMinutes = minutes;
}
if (hours < 10){
displayHours = "0" + hours;
} else {
displayHours = hours;
}
let stopwatchNow = displayHours + ":" + displayMinutes + ":" + displaySeconds;
document.getElementById("front-2").innerHTML = stopwatchNow;
}
Hello at the start of your stopwatch function you set
let hours = 0;
let minutes = 0;
let seconds = 0;
let displayHours = 0;
let displayMinutes = 0;
let displaySeconds = 0;
and that's what you display later in the code, you need to define this variables outside of this function
This is because in function stopwatch, every time this function runs you set
let hours = 0;
let minutes = 0;
let seconds = 0;
let displayHours = 0;
let displayMinutes = 0;
let displaySeconds = 0;
These variables will always be 0, since you set them when function runs. In order to fix this, you need to move them outside the function:
let hours = 0;
let minutes = 0;
let seconds = 0;
let displayHours = 0;
let displayMinutes = 0;
let displaySeconds = 0;
function stopwatch(){
// removed
seconds++; // this stays here
// the rest of your code goes in here
}
This way your variables won't reset to 0 when function starts to run
<div id="container-2">
<div id="clock-2">
<span id="front-2">00:00:00</span>
--- >>
<span id="back-2">88:88:88</span>
</div>
</div>
<div class="buttons-2">
<button id="button-left-2" onclick="myFunction()"><i class="fas fa-stopwatch"></i>fun</button>
<button id="button-stop-2" onclick="stopSW()"><i class="fa-solid fa-stop"></i>stop</button>
<button id="button-play-2" onclick="startSW()"><i class="fa-solid fa-play"></i>start</button>
<button id="button-right-2" onclick="reset()"><i class="fa-solid fa-delete-left"></i>reset</button>
</div>
<script>
function myFunction() {
var node = document.getElementById("back-2");
display(node);
}
var start;
function startSW() {
clearInterval(start);
start = setInterval(stopwatch, 1000);
}
function stopSW() {
clearInterval(start);
}
function reset(){
clearInterval(start);
document.getElementById("front-2").innerHTML = "00:00:00";
document.getElementById("back-2").innerHTML = "00:00:00";
hours = 0;
minutes = 0;
seconds = 0;
}
var hours = 0;
var minutes = 0;
var seconds = 0;
function stopwatch() {console.log('stopwatch')
seconds++;
if(seconds == 60){
seconds = 0;
minutes++;
if(minutes == 60) {
minutes = 0;
hours++;
}
}
display();
}
function display(node){
let displayHours = 0;
let displayMinutes = 0;
let displaySeconds = 0;
if (seconds < 10){
displaySeconds = "0" + seconds;
} else {
displaySeconds = seconds;
}
if (minutes < 10){
displayMinutes = "0" + minutes;
} else {
displayMinutes = minutes;
}
if (hours < 10){
displayHours = "0" + hours;
} else {
displayHours = hours;
}
let stopwatchNow = displayHours + ":" + displayMinutes + ":" + displaySeconds;
if(!node)node=document.getElementById("front-2");
node.innerHTML = stopwatchNow;
}
</script>
there were a variety of mistakes,
clearInterval not being given the correct value
the time variables needed to be declared in global scope
i can only guess what myfunction is supposed to be doing
etc...
have fun
Building a countdown Timer with rounds, working and resting for training.
Issue: My timer seems to start fine (with the user inputted values) after the first round, once rest is done, my working timer doesn't start at the inputted value like it should. It's always one number short.
E.g If you input 5: 10: 10. When it comes back around, it will appear one number shorter than it should 4: 09: 00
From the left the Timer is rounds, working, rest.
Please help.
let rnd = '00';
let wrk = 00; // this will act as my seconds
let rst = '00';
let prepare =3;
let interval;
let rstInterval;
let startTimer = '00';
// store the working set in an array
let prepIn = document.getElementById('prep');
prepIn.innerHTML = prepare;
// buttons
document.getElementById('start').addEventListener('click', initTimer);
document.getElementById('pause').addEventListener('click', pauseTimer);
document.getElementById('reset').addEventListener('click', finishTimer);
let span= document.getElementById('app').getElementsByTagName('span');
function initTimer(){
clearInterval(interval)
let rounds = document.querySelector('.rounds').value;
rnd = rounds;
span[0].innerHTML = rnd
let work = document.querySelector('.work').value;
wrk = work;
startTimer = work;
span[1].innerHTML =wrk
let rest = document.querySelector('.rest').value;
rst = rest;
span[2].innerHTML = rst
console.log(startTimer)
interval= setInterval(countDown, 1000);
}
// Pause the timer
function pauseTimer(){
clearInterval(interval);
console.log("pauseTimer")
}
// reset timer
function finishTimer(){
clearInterval(interval);
span[0].innerHTML = '00'
span[1].innerHTML = '00'
span[2].innerHTML = '00'
rnd = '00';
wrk = '00';
rst = '00';
document.querySelector('.timeNum').style.display = "flex"
}
function countDown(){
prepare--
if(prepare < 10){
prepIn.innerHTML = '0' + prepare;
}
if(prepare >=9){
prepIn.innerHTML = prepare;
}
if(prepare <= 3){
prepIn.style.color = 'green';
}
if(prepare < 1){
clearInterval(interval)
prepare = 00
prepIn.style.display = 'none'
clearInterval(startTimer)
startTimer= setInterval(timerActive, 1000);
let work = document.querySelector('.work').value;
wrk = work;
console.log(wrk)
}
document.querySelector('.timeNum').style.display = "none";
}
function timerActive(){
wrk--
if(wrk <=9){
span[1].innerHTML = '0' + wrk;
}
if(wrk >=10){
span[1].innerHTML = wrk;
}
if(wrk <= 0){
clearInterval(startTimer)
let rest = document.querySelector('.rest').value;
rst = rest
let rstInterval = setInterval(() => {
rst--
if(rst<=9){
span[2].innerHTML = '0' + rst;
}
if(rst >=10){
span[2].innerHTML = rst;
}
if(rst < 1){
clearInterval(rstInterval)
rstcount();
}
},1000)
rnd--
if(rnd <10){
span[0].innerHTML = '0'+ rnd;
}
else{
span[0].innerHTML = rnd;
}
}
};
function rstcount(){
clearInterval(rstInterval);
countDown();
}
<div class="timer">
<div class="numb">
<h2 id="prep"></h2>
<h2 id="app"><span>00</span>:<span>00</span>:<span>00</span></h2>
<h1 class="timeNum"><input type='number' min="00" max="99" class="rounds" value='00'>:<input type='number' min="00" max="99" class="work" value="00">:<input type='number' min="00" max="99" class="rest" value="00"></h1>
<div class="buttons">
<input type="button" id="start" value="Start">
<input type="button" id="pause" value="Pause">
<input type="button" id="reset" value="Reset">
</div>
</div>
</div>
So I have the following code, As you can see in the HTML I have a div with id=clock and an input element also with id=clock, basically if i remove the div or comment it out, the input element works fine, on the html page the clock in the input element will display the time, I would prefer it to use the div element for styling purposes; however, if i comment out the input element and use the div it does not count up, I think I understand why but I cant seem to fix it. Can someone help explain how I can do this using the following code?
var flagclock = 0;
var flagstop = 0;
var stoptime = 0;
var splitcounter = 0;
var currenttime;
var splitdate = '';
var output;
var clock;
// Start-Stop Function
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 = '';
}
}
//Increment function
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.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;
}
// reset function
function resetclock() {
flagstop = 0;
stoptime = 0;
splitdate = '';
window.clearTimeout(refresh);
output.value = '';
splitcounter = 0;
if (flagclock == 1) {
var resetdate = new Date();
var resettime = resetdate.getTime();
counter(resettime);
} else {
clock.value = "00:00:0";
}
}
//Split function
function splittime() {
if (flagclock == 1) {
if (splitdate != '') {
var splitold = splitdate.split(':');
var splitnow = clock.value.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;
}
var mzeros = (numbers[0][1] - numbers[0][0]) < 10 ? '0' : '';
var szeros = (numbers[1][1] - numbers[1][0]) < 10 ? '0' : '';
output.value += '\t+' + mzeros + (numbers[0][1] - numbers[0][0]) + ':' + szeros + (numbers[1][1] - numbers[1][0]) + ':' + (numbers[2][1] - numbers[2][0]) + '\n';
}
splitdate = clock.value;
output.value += (++splitcounter) + '. ' + clock.value + '\n';
}
}
<input id="startstopbutton" class="buttonZ" style="width: 120px;" type="button" name="btn" id='btn' value="Start" onclick="startstop()" ;>
<input id="resetbutton" class="buttonZ" style="width: 120px;" type="button" name="btnRst1" id='btnRst1' value="Reset" onclick="resetclock()" ;>
<div id="clock" class="timerClock">00:00:00</div><br>
<!-- Clock 2 -->
<input id="clock" class="timerClock" type="text" value="00:00:0" style="text-align: center;" readonly=""><br>
<!-- Split Button -->
<input id="splitbutton" class="buttonZ" style="width: 120px; margin-right: 170px" type="button" value="Split Time" onclick="splittime();">
<!-- output for split times -->
<textarea id="output" spellcheck="false"></textarea>
You are using clock.value to set the contents of the <input> element. This will not work for <div> elements; you will need to use innerHTML instead:
clock = document.getElementById('clock'); //div#clock
// ...
clock.innerHTML = formattime(timediff, '');
have a div with id=clock and an input element also with id=clock,
This is bad. ID have to be UNIQUE. This is why when you have both present ( with same id ) the counter doesn't work. It selects just the first element with id clock which is the div.
It doesn't select the input. As you can see getElementById is singular. If you want to select both of them, add a common class and select that with getElementsByClassName(className) ( notice the plural Elements compared to Element from the ID selector ) or querySelectorAll(className) and loop through them.
I added clock-div as the id on the div
Also. div element does not have a value attribute ( unlike input ). To get or edit/manipulate the text inside a div element you should use div.innerText instead of div.value. As a side note, div can have HTML inside it (input can't) . You can access it with div.innerHTML
So basically you need to change the id of the div ( if you also want to keep the input ) and change clock.value to clock.innerText everywhere.
Another option would be to keep both input and div. And assign the value of the input to the div.innerText.
var flagclock = 0;
var flagstop = 0;
var stoptime = 0;
var splitcounter = 0;
var currenttime;
var splitdate = '';
var output;
var clock;
// Start-Stop Function
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 = '';
}
}
//Increment function
function counter(starttime) {
output = document.getElementById('output');
// change here id
clock = document.getElementById('clock-div');
currenttime = new Date();
var timediff = currenttime.getTime() - starttime;
if (flagstop == 1) {
timediff = timediff + stoptime
}
if (flagclock == 1) {
clock.innerText = 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;
}
// reset function
function resetclock() {
flagstop = 0;
stoptime = 0;
splitdate = '';
window.clearTimeout(refresh);
output.value = '';
splitcounter = 0;
if (flagclock == 1) {
var resetdate = new Date();
var resettime = resetdate.getTime();
counter(resettime);
} else {
clock.innerText = "00:00:0";
}
}
//Split function
function splittime() {
if (flagclock == 1) {
if (splitdate != '') {
var splitold = splitdate.split(':');
var splitnow = clock.value.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;
}
var mzeros = (numbers[0][1] - numbers[0][0]) < 10 ? '0' : '';
var szeros = (numbers[1][1] - numbers[1][0]) < 10 ? '0' : '';
output.value += '\t+' + mzeros + (numbers[0][1] - numbers[0][0]) + ':' + szeros + (numbers[1][1] - numbers[1][0]) + ':' + (numbers[2][1] - numbers[2][0]) + '\n';
}
splitdate = clock.innerText;
output.innerText += (++splitcounter) + '. ' + clock.value + '\n';
}
}
<input id="startstopbutton" class="buttonZ" style="width: 120px;" type="button" name="btn" id='btn' value="Start" onclick="startstop()" ;>
<input id="resetbutton" class="buttonZ" style="width: 120px;" type="button" name="btnRst1" id='btnRst1' value="Reset" onclick="resetclock()" ;>
<div id="clock-div" class="timerClock">00:00:00</div><br>
<!-- Clock 2 -->
<input id="clock" class="timerClock" type="text" value="00:00:0" style="text-align: center;" readonly=""><br>
<!-- Split Button -->
<input id="splitbutton" class="buttonZ" style="width: 120px; margin-right: 170px" type="button" value="Split Time" onclick="splittime();">
<!-- output for split times -->
<textarea id="output" spellcheck="false"></textarea>
This is what happens when I embed the JsFiddle into my website as a result:
http://i.imgur.com/JkDefod.png
What can I do so that my embedded JsFiddle only shows the running program and not the extra text above?
Here is my JsFiddle code:
var handler = function() {
if (--sec < 0) {
sec = 59;
if (--min < 0) {
min = 0;
sec = 0;
}
}
var min1 = "0" + min + "m";
var min2 = min + "m";
var sec1 = "0" + sec + "s";
var sec2 = sec + "s";
document.getElementById("time").innerHTML = (min < 10 ? min1.fontcolor("red") : min2.fontcolor("red")) + ":".fontcolor("red") + (sec < 10 ? sec1.fontcolor("red") : sec2.fontcolor("red"));
};
var sec = 0;
var min = 15;
handler();
setInterval(handler, 1000);
<div id="worked"></div>
<h1 style="text-align: center;"><span style="color: #ff0000;"><strong>Offer Ends In:</strong></span></h1>
<h1 id="time" style="text-align: center;"> </h1>
You can directly add this code in your page, or using the JsFiddle embeded, do like this:
<div class="someClass">
<script async src="//jsfiddle.net/DiogoBernardelli/vuc85mok/embed/result/"></script>
</div>
And add this in your Stylesheet (.css) file:
.someClass iframe {
height: 200px //you can manually change this height
}
If you want to add only this countdown timer on your web-page, why don't you add your JS code in the tags after your divs?
Something like this:
<body>
<div id="worked"></div>
<h1 style="text-align: center;"><span style="color: #ff0000;"><strong>Offer Ends In:</strong></span></h1>
<h1 id="time" style="text-align: center;"> </h1>
</body>
<script>
var handler = function() {
if (--sec < 0) {
sec = 59;
if (--min < 0) {
min = 0;
sec = 0;
}
}
var min1 = "0" + min + "m";
var min2 = min + "m";
var sec1 = "0" + sec + "s";
var sec2 = sec + "s";
document.getElementById("time").innerHTML = (min < 10 ? min1.fontcolor("red") : min2.fontcolor("red")) + ":".fontcolor("red") + (sec < 10 ? sec1.fontcolor("red") : sec2.fontcolor("red"));
};
var sec = 0;
var min = 15;
handler();
setInterval(handler, 1000);
</script>
This question already has answers here:
How to create an accurate timer in javascript?
(15 answers)
Closed 6 years ago.
I am building an activity timer, but the code I have is not working properly. The timer is going ~40% faster than real time. What's going wrong?
var sec = 00;
var min = 00;
var hr = 00;
var t;
var timer_is_on = 0;
function timedCount() {
if (min == 0) {
min = 1;
}
document.getElementById('seconds').value = sec;
document.getElementById('minutes').value = min;
$('.node-form .form-item:nth-child(4) input').val(min);
document.getElementById('hours').value = hr;
$('.node-form .form-item:nth-child(3) input').val(hr);
sec = sec + 1;
if (sec == 60) {
sec = 0;
min = min + 1;
if (min == 60) {
min = 1;
hr = hr + 1;
}
}
t = setTimeout("timedCount()", 1000);
}
function doTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
function resetCount() {
stopCount();
sec = 0;
min = 0;
hr = 0;
document.getElementById('hours').value = 00;
$('.node-form .form-item:nth-child(3) input').val('0');
document.getElementById('minutes').value = 00;
$('.node-form .form-item:nth-child(4) input').val('0');
document.getElementById('seconds').value = 00;
}
function putInTimelog() {
// Put hours
var hourItems = [];
var hourFields = document.getElementById("node-form").getElementsByTagName("input");
for (var i = 0; i < hourFields.length; i++) {
//omitting undefined null check for brevity
if (hourFields[i].id.lastIndexOf("edit-field-timelog-hours-0-value-", 0) === 0) {
hourItems.push(hourFields[i]);
}
}
var hourField = 'edit-field-timelog-hours-0-value-';
hourField = hourField.concat(hourItems.length);
document.getElementById(hourField).value = hr;
// Put minutes
var minuteItems = [];
var hourFields = document.getElementById("node-form").getElementsByTagName("input");
for (var i = 0; i < hourFields.length; i++) {
//omitting undefined null check for brevity
if (hourFields[i].id.lastIndexOf("edit-field-timelog-minutes-0-value-", 0) === 0) {
minuteItems.push(hourFields[i]);
}
}
var minuteField = 'edit-field-timelog-minutes-0-value-';
minuteField = minuteField.concat(minuteItems.length);
alert(minuteField);
alert((minuteField).length);
document.getElementById(minuteField).value = min;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<span class="timer-title"><strong>Activity timer</strong></span>h:
<input id="hours" readonly="readonly" size="2" type="text" /> m:
<input id="minutes" readonly="readonly" size="2" type="text" /> s:
<input id="seconds" readonly="readonly" size="2" type="text" /><span class="timer-buttons"><input onclick="doTimer()" type="button" value="Start" /> <input onclick="stopCount()" type="button" value="Stop" /> <input onclick="resetCount()" type="button" value="Reset" /> </span>
</form>
View on JSFiddle
clock.js is my repo that might help when used in conjunction with window.setInterval(). Working example included.
Add <script src="https://rack.pub/clock.min.js"></script> to your HTML then call clock.now --> 1462248501241 each time you want a time snapshot. You can add and subtract intuitively from there.
The actual js looks like:
var clock = (function() {
// object to expose as public properties and methods such as clock.now
var pub = {};
//clock.now
Object.defineProperty(pub, "now", {
get: function () {
return Date.now();
}
});
//API
return pub;
}());
var doc = document;
var el = doc.getElementById('output');
window.setInterval(function(){
/// call your function here
el.innerHTML = clock.what.time(clock.now);
}, 500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rack.pub/clock.min.js"></script>
<h2 id='output'></h2>