I've made a stopwatch in JavaScript, and i'm showing it through h1 tag of HTML and i'm able to get it's textContent with following code in JS.
<h1 id="time">00:00:00</h1>
var h1 = document.getElementById('time'),
getTimer = h1.textContent;
Which fetches the value perfectly, but the problem is when i hit the start button to run the stopwatch and then if click getTime button it still fetches the static value of h1 tag that is 00:00:00, which is not what i'm looking for.I want to fetch the current value of h1 tag which is updating constantly. Suppose i clicked on start button and then after 10sec if i click on getTime i want 00:00:10 as the value of getTimer variable but in my case it's showing only 00:00:00.
Here's the working codepen demo for the same.
var h1 = document.getElementById('time'),
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0, hours = 0,
t,
getTimer = document.getElementById('time').textContent,
fetchVal = document.getElementById('fetchVal'),
form = document.getElementById('form');
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
t = setTimeout(add, 1000);
}
/* Start button */
start.onclick = timer;
/* Stop button */
stop.onclick = function() {
clearTimeout(t);
}
/* Clear button */
clear.onclick = function() {
h1.textContent = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
}
form.addEventListener('submit', function(e){
e.preventDefault();
alert(getTimer);
});
<form action="#" id="form">
<h1 id="time">00:00:00</h1>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
<button type="submit" id="fetchVal">Get Time</button>
</form>
How do i get the current value of h1 tag? I'm looking for solution in pure JS
Thanks in advance for the help.
getTimer = document.getElementById('time').textContentis your page loaded value00:00:00,so will always get that value !!! Should changegetTimer = document.getElementById('time')andalert(getTimer.textContent