I wanna use it on multiple HTML elements but have not had any luck, like have a 2nd element that countsdown to a different time
Because I tried to change all the variable names in the 2nd script (copy of the script with HTML element id changed, variable and function names changed) and it was giving no output.
This is it
(function() {
var start = new Date;
start.setHours(15, 10, 0); // 11pm
function pad(num) {
return ("0" parseInt(num)).substr(-2);
}
function tick() {
var now = new Date;
if (now > start) { // too late, go to tomorrow
start.setDate(start.getDate() 1);
}
var remain = ((start - now) / 1000);
var hh = pad((remain / 60 / 60) % 60);
var mm = pad((remain / 60) % 60);
var ss = pad(remain % 60);
document.getElementById('time').innerHTML =
hh ":" mm ":" ss;
setTimeout(tick, 1000);
}
document.addEventListener('DOMContentLoaded', tick);
})();
</script>
CodePudding user response:
Make it a function, find the elements then pass the elements to the countdown timer which then mutates the elements innerHTML etc.
If you want different times then use data
attributes to set params on the element which you can get from elm.dataset.somename
, see docs
function countdown(elm) {
var start = new Date;
start.setHours(elm.dataset.h || 0, elm.dataset.m || 0, elm.dataset.s || 0); // from dataset
function pad(num) {
return ("0" parseInt(num)).substr(-2);
}
function tick() {
var now = new Date;
if (now > start) { // too late, go to tomorrow
start.setDate(start.getDate() 1);
}
var remain = ((start - now) / 1000);
var hh = pad((remain / 60 / 60) % 60);
var mm = pad((remain / 60) % 60);
var ss = pad(remain % 60);
elm.innerHTML =
hh ":" mm ":" ss;
setTimeout(tick, 1000);
}
tick();
}
document.querySelectorAll('.timer').forEach(countdown)
<div class="timer" data-h="1" data-m="10" data-s="0"></div>
<div class="timer" data-h="3" data-m="15" data-s="5"></div>
<div class="timer" data-h="6" data-m="20" data-s="10"></div>
<div class="timer" data-h="12" data-m="30" data-s="59"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>