Your
updateClock
method sets the same remaining time in every
.section
element in your document. You need to change it so that it only sets the time for the related element.
You'll also find that
onload
doesn't work for
<div>
elements. Your code currently calls the
initializeClock
method directly from the
postsItem
method, and inserts
onload="undefined"
into the HTML output. Instead, you should initialize the clocks after you have inserted them into the document.
For example:
function initializeClock(counter){
function updateClock(){
const endTime = counter.dataset.endTime;
const t = getRemainingTime(endTime);
if (t.total <= 0) {
clearInterval(timeinterval);
counter.innerHTML = "The countdown is over!"
return;
}
const daysSpan = counter.getElementsByClassName('di');
const hoursSpan = counter.getElementsByClassName('ho');
const minutesSpan = counter.getElementsByClassName('mi');
const secondsSpan = counter.getElementsByClassName('se');
daysSpan[0].innerHTML = ('0' + t.days).slice(-2) + ' DAY(S)';
hoursSpan[0].innerHTML = ('0' + t.hours).slice(-2) + ' HR(S)';
minutesSpan[0].innerHTML = ('0' + t.minutes).slice(-2) + ' MIN(S)';
secondsSpan[0].innerHTML = ('0' + t.seconds).slice(-2) + ' SEC(S)';
}
updateClock();
const timeinterval = setInterval(updateClock, 1000);
}
function postsItem(post) {
return `<section>
<h2 class="article-ttitle">${post.title}</h2>
<article>
<div data-end-time="${post.endTime}">
<span class="di"></span> Days
<span class="ho"></span> Hours
<span class="mi"></span> Minutes
<span class="se"></span> Seconds
<div>
</article>
</section>`;
}
const container = document.getElementById('posts');
container.innerHTML = `${posts.map(postsItem).join('')}`;
container.querySelectorAll("div[data-end-time]").forEach(initializeClock);
Demo[
^]