Last active
July 8, 2019 04:31
-
-
Save jcchikikomori/2be871014d9d8a508b7198600519d63c to your computer and use it in GitHub Desktop.
Native JavaScript Countdown script (JQuery required. Will be updated very soon)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* John Cyrill Corsanes | |
* https://jsfiddle.net/jccultima123/L4tdpuc6/ | |
* | |
* NOTE: Manually set this function with intervals on target pages | |
* to avoid issues came from turbolinks | |
* | |
* SAMPLE: | |
* ``` | |
* $(function() { | |
* setInterval(() => { | |
* countDown('#dateTimeCountdown', $('#activePromoEnd').val()); | |
* }, 1000); | |
* }); | |
* ``` | |
* TODO: Native element selector | |
* | |
* @param {String} elementStr -- Should be `span` or `p` | |
* @param {String} endDateTime | |
*/ | |
function countDown(elementStr, endDateTime = null) { | |
// params | |
var startDateTime = new Date(); | |
var endDateTime = new Date(endDateTime); | |
// Time remaining (difference) | |
var timeRemaining = (endDateTime - startDateTime); | |
// Update if has difference, otherwise hide | |
if (timeRemaining > 0) { | |
// Formula | |
var a_day = 24 * 60 * 60 * 1000; | |
// Compute by days | |
var d = Math.floor(timeRemaining / a_day) | |
// Compute by hours | |
var h = Math.floor((timeRemaining % a_day) / (60 * 60 * 1000)) | |
// Compute by minutes | |
var m = Math.floor((timeRemaining % a_day) / (60 * 1000)) % 60 | |
// Compute by seconds | |
var s = Math.floor((timeRemaining % a_day) / 1000) % 60 % 60 | |
// Put text | |
var result = d + ' days, ' + h + ' hours, ' + m + ' minutes, ' + s + ' seconds' | |
$(elementStr).text(result).parent().removeClass("hide").show(); | |
} else { | |
// Hide container | |
$(elementStr).parent().hide(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment