Precept toast: Countdown

In this project, I enhanced a custom website toast on a WordPress site by adding a countdown timer feature. The timer counts down to a specific time that can be set in the UI by the user. For countdowns less than 24 hours away, there is an option to exclude the day number, providing a more streamlined display. The existing elements of the toast, such as the headline, description, and call-to-action (CTA), were left intact to ensure consistency while integrating the new functionality.

A countdown timer on a website toast modal

Requirements

The toast needed to count down to a specified point in time while adhering to style guidelines and allowing the signed-in user to easily select options for the toast from the WordPress dashboard.

Solution

I used the Advanced Custom Fields plugin to add options to the user interface of the custom post type for website toasts. Within the template file, I added a small snippet of JavaScript to decrement the timer.

document.addEventListener('DOMContentLoaded', () => {
	let countdownDate = new Date(document.getElementById('campaign-countdown').dataset.countdown).getTime();
	let timerX = setInterval(function() {
		let now = new Date().getTime();
		let duration = countdownDate - now;
		document.querySelector('#campaign-countdown .days .number').innerHTML = formatTimer(Math.floor(duration / (1000 * 60 * 60 * 24)));
		document.querySelector('#campaign-countdown .hours .number').innerHTML = formatTimer(Math.floor((duration % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)));
		document.querySelector('#campaign-countdown .minutes .number').innerHTML = formatTimer(Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60)));
		document.querySelector('#campaign-countdown .seconds .number').innerHTML = formatTimer(Math.floor((duration % (1000 * 60)) / 1000));
		if (duration < 0) {
			clearInterval(timerX);
			document.querySelectorAll('#campaign-countdown .number').forEach(num => num.innerHTML = '00');
		}
	}, 1000);
	function formatTimer(n) { return (n < 10) ? '0' + n : n }
})
A countdown timer on a website toast modal on Precept.org

Conclusion

The countdown feature works very well and is used often to countdown to the end of fundraising campaigns.