Skip to content

Instantly share code, notes, and snippets.

@HasStacey
Last active August 16, 2020 08:30
Show Gist options
  • Save HasStacey/2fc2612678000088a33e to your computer and use it in GitHub Desktop.
Save HasStacey/2fc2612678000088a33e to your computer and use it in GitHub Desktop.
Create a JS countdown timer driven by PHP variables
<?php
$year = 2014;
$month = 10;
$day = 21;
$hour = 14;
$min = 00;
$sec = 00;
$target = mktime($hour, $min, $sec, $month, $day, $year);
$current = time();
$difference = $target - $current;
$rDay = floor($difference/60/60/24);
$rHour = floor(($difference-($rDay*60*60*24))/60/60);
$rMin = floor(($difference-($rDay*60*60*24)-$rHour*60*60)/60);
$rSec = floor(($difference-($rDay*60*60*24)-($rHour*60*60))-($rMin*60));
?>
<script type="text/javascript">
var days = <?php echo $rDay; ?>
var hours = <?php echo $rHour; ?>
var minutes = <?php echo $rMin; ?>
var seconds = <?php echo $rSec; ?>
function countdown(){
seconds--;
if (seconds < 0){
minutes--;
seconds = 59
}
if (minutes < 0){
hours--;
minutes = 59
}
if (hours < 0){
days--;
hours = 23
}
function pad(n) {
if ( n < 10 && n >= 0 ) {
return "0" + n;
} else {
return n;
}
}
document.getElementById("countdown").innerHTML = pad(days)+":"+pad(hours)+":"+pad(minutes)+":"+pad(seconds);
setTimeout ( "countdown()", 1000 );
}
</script>
// Add this to your markup wherever you want the countdown to appear. Can appear on any text element.
<h1 id="countdown"></h1>
// The <body> element needs this: onload="countdown();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment