I'm working on a page on my wordpress site where i pull data from the backend. The data has an end_date
column that i use to display a countdown timer i.e. from the current date time till the end_date
.
This is how i approach it:
This is the html element that will display the timer:
<div class="t1-auction-timer"></div>
This is the javascript that creates the timer:
var countDownDate = new Date("<?=$endDate?>").getTime(); var x = setInterval(function() { var now = new Date().getTime(); var distance = countDownDate - now; var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); var timer = document.querySelectorAll(".t1-auction-timer"); for (var i = 0; i < timer.length; i++) { timer[i].innerHTML = '<ul class="clock-value"><li class="clock-days">' + padNumber(days) + '<small>days</small> </li><li class="clock-separator">:</li><li class="clock-hours"> ' + padNumber(hours) + ' <small>hrs</small> </li><li class="clock-separator">:</li><li class="clock-minutes"> ' + padNumber(minutes) + ' <small>min</small> </li><li class="clock-separator">:</li><li class="clock-seconds"> ' + padNumber(seconds) + ' <small>sec</small> </li></ul>'; } if ( distance < 0 ) { clearInterval(x); for (var i = 0; i < timer.length; i++) { timer[i].innerHTML = "EXPIRED"; } } }, 1000); function padNumber(number) { if( number == 0 ) { number = "0" + number; } else if( number > 9 ) { number; } else { number = "0" + number; } return number; }
The <?=$endDate?>
variable is passed from php. Its being passed correctly.
The number of timers to be displayed will be dynamic depending on the records in the database. The issue I'm facing is: I only get timer created from the first record. Its duplicated across all posts being displayed on the page. I suspect this has to do with my .t1-auction-timer
class loop but I haven't figured it out yet.
没有评论:
发表评论