Skip to content

Instantly share code, notes, and snippets.

@ngnam
Forked from chriskonnertz/Countdown.js
Created June 14, 2023 10:07
Show Gist options
  • Save ngnam/b8f24da570f5661ec3b58340f2d6d57a to your computer and use it in GitHub Desktop.
Save ngnam/b8f24da570f5661ec3b58340f2d6d57a to your computer and use it in GitHub Desktop.
Simple JavaScript Countdown Snippet
<div class="countdown" data-datetime="<?php echo time() ?>">
<span class="days">0</span> days
<span class="hours">0</span> hours
<span class="minutes">0</span> minutes
<span class="seconds">0</span> seconds
</div>
<script>
(function()
{
function updateCountdown()
{
$('.countdown').each(function()
{
var timestamp = parseInt(jQuery(this).attr('data-datetime')) * 1000;
var target = new Date();
var now = new Date();
target.setTime(timestamp);
var totalMilliSeconds = target.getTime() - now.getTime();
if (totalMilliSeconds < 0) return;
var totalSeconds = parseInt(totalMilliSeconds / 1000);
var seconds = totalSeconds % 60;
var totalMinutes = parseInt(totalSeconds / 60);
var minutes = totalMinutes % 60;
var totalHours = parseInt(totalMinutes / 60);
var hours = totalHours % 24;
var totalDays = parseInt(totalHours / 24);
var days = totalDays;
$(this).find('.days').text(days);
$(this).find('.hours').text(hours);
$(this).find('.minutes').text(minutes);
$(this).find('.seconds').text(seconds);
});
window.setTimeout(updateCountdown, 1000);
}
updateCountdown();
})();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment