I have an events website and would like to add a countdown ticker.
The ticker appears on my Events Collection page, and I would like it to countdown to the Event date and time - which is a date/time field with an added time picker.
Presumably I’ll need some JavaScript - I will continue to look for solutions online but if anybody has some experience getting a countdown working off a CMS Date/Time field then please let me know. Thanks
Glad you have found solution. As this forum is full of solutions for many different requests Next time try to use keyword “countdown” in search input of this forum and you will find many working examples.
So my countdown is working using the following embed (from Finsweet):
<script>
(function () {
const second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24;
// Set the target date and time for the countdown (format: "MM/DD/YYYY HH:mm:ss")
const targetDateString = "{CMSDateField}";
const targetDate = new Date(targetDateString).getTime();
const updateCountdown = () => {
const now = new Date().getTime(), // Get the current date and time
distance = targetDate - now; // Calculate the time remaining until the target date
// Update the HTML elements with the remaining time
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);
// Check if the target date has already passed
if (distance < 0) {
clearInterval(interval); // Stop the countdown timer
document.getElementById('days').innerText = '0';
document.getElementById('hours').innerText = '0';
document.getElementById('minutes').innerText = '0';
document.getElementById('seconds').innerText = '0';
// You can display an element at the end of the countdown with this ID
document.getElementById('todaymessage').style.display = 'block';
}
};
// Initial call to update countdown
updateCountdown();
// Update the countdown every second
const interval = setInterval(updateCountdown, 1000);
})();
</script>
I’m having trouble with the part commented: // Check if the target date has already passed
For example, I have an event that has the date of June 18th (today).
I was hoping that the countdown numbers would all show 0, and the todaymessage (which is set to display:none), would show as display:block.
What’s actually happening is the todaymessage is staying hidden, and the numbers are showing as negative:
I appreciate that this is more of a JS related question, and the answer may be obvious enough by looking at the code… but I assumed it would just work.