4
Hey, guys. All right?
I have a chronometer that is in javascript and I want it to appear more than once on a specific page.
The problem is that it works only the first time it appears on the page.
I imagine it’s because of the ids that are duplicated on the html page (id="days" id="hours" id="minutes" id="Seconds") when I try to duplicate the second stopwatch. But if I want to call the timers I need to use these ids.
To try to get around the problem I tried using getElementsByClassName() instead of getElementById(). So I could use classes instead of ids in my HTML. So, I could call the javascript code through the class more than once, no problem. However, my code did not work with getElementsByClassName(). The timer simply does not appear when I try to use this function.
Does anyone have any solution for this stopwatch to work more than once on the same page?
var today = new Date();
var dd = String(today.getDate() + 1).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = mm + ' ' + dd + ', ' + yyyy;
const second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24;
let countDown = new Date(today).getTime(),
x = setInterval(function() {
let now = new Date().getTime(),
distance = countDown - now;
document.getElementById('days').innerText = Math.floor(distance / (day)),
document.getElementById('hours').innerText = Math.floor((distance % (day)) / (hour)),
document.getElementById('minutes').innerText = Math.floor((distance % (hour)) / (minute)),
document.getElementById('seconds').innerText = Math.floor((distance % (minute)) / second);
}, second)
<div class="conteiner-countdown-loop">
<ul>
<li class="countdown-loop"><span id="days"></span>dias</li>
<li class="countdown-loop"><span id="hours"></span>Horas</li>
<li class="countdown-loop"><span id="minutes"></span>Minutos</li>
<li class="countdown-loop"><span id="seconds"></span>Segundos</li>
</ul>
</div>
Hello, Bacco. All right? For some reason, this code stopped working from yesterday to today. I tried to understand the problem but could not. I suppose it is in the function that gets today’s date. Could you give me a light? I thank you for your attention.
– Carlos Guimarães