How To Make Mulitple Count Down Clocks?
This is what I have. Some people have suggested I should use a class instead of an id which is true. On the other hand if I use a class I don't know if getelementsbyclassname even
Solution 1:
When handling elements by class you might want to use:
Document.getElementsByClassName("selector")
orParentNode.querySelectorAll(".selector")
than you need to loop over the returned NodeList collection and assign values.
in ES6 you can use
[...myNodeList].forEach( node => {
/* do something to node */
});
in good old JS it would look like:
for ( var i = 0; i < myNodeList.length; i++ ) {
/* do something to myNodeList[i] */
}
// Set the date we're counting down to
var countDownDate = new Date("Sep 5, 2018 15:37:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var dif = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var d = Math.floor(dif / (1000 * 60 * 60 * 24));
var h = Math.floor((dif % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var m = Math.floor((dif % (1000 * 60 * 60)) / (1000 * 60));
var s = Math.floor((dif % (1000 * 60)) / 1000);
var formatted = d + "d " + h + "h " + m + "m " + s + "s ";
// Output the result in an element with class="demo"
[...document.querySelectorAll(".demo")].forEach(el => el.innerHTML = dif < 0 ? "EXPIRED" : formatted );
// If the count down is over, stop the interval
if (dif < 0) {
clearInterval(x);
}
}, 1000);
<p class="demo"></p>
<p class="demo"></p>
<p class="demo"></p>
Solution 2:
First, your HTML is invalid, an id
should be unique. Let's change the items to class
:
<p class="demo"></p>
<p class="demo"></p>
<p class="demo"></p>
Second, it is getElementsByClassName
, not getelementsbyclassname
. Javascript is case-sensitive.
Now, let's see how one can work with this:
var clocks = document.getElementsByClassName("demo");
var x = setInterval(function() {
for (var clockIndex = 0; clockIndex < clocks.length; clockIndex++) {
//Handle the clock identified by clocks[clockIndex]
//If the given clock is expired, then continue;
//If all of them are expired, then clearInterval(x);
}
}, 1000);
Post a Comment for "How To Make Mulitple Count Down Clocks?"