Skip to content

Instantly share code, notes, and snippets.

@antronic
Created March 31, 2020 10:18
Show Gist options
  • Save antronic/e71504fdbbc41f017b3410a7937ce910 to your computer and use it in GitHub Desktop.
Save antronic/e71504fdbbc41f017b3410a7937ce910 to your computer and use it in GitHub Desktop.
Idea for inject embedded countdown DOM element
(function() {
const today = new Date()
const _targetTime = prompt('Input your end time', `${today.getMonth() + 1}/${today.getDate()}/${today.getFullYear()} ${today.getHours()}:${today.getMinutes()}:${today.getSeconds()}`)
const targetTime = new Date(_targetTime)
if (isNaN(targetTime)) {
throw new Error('Your time input is invalid date format.')
}
// Create Clock wrapper
const clockContainer = document.createElement('DIV')
clockContainer.style = `
position: fixed;
top: 24px;
right: 24px;
z-index: 1024;
padding: 18px;
background: #fff;
`
// Create Clock element
const clockElement = document.createElement('DIV')
const clockText = document.createElement('SPAN')
clockText.style = 'font-size: 18pt;'
const clockTextId = 'clock-countdown-txt'
clockText.id = clockTextId
clockElement.appendChild(clockText)
clockContainer.appendChild(clockElement)
document.body.appendChild(clockContainer)
const _clockText = document.querySelector(`#${clockTextId}`)
// Function
const formatNumber = num => Number(num) > 9 ? num : '0' + num
function setTime(hh, mm, ss) {
_clockText.textContent = `${formatNumber(hh)}:${formatNumber(mm)}:${formatNumber(ss)}`
}
// !!! NEED TO APPLY
function calculateDiff() {
// return difference time in hour, minute, second
return { hour: 6, minute: 30, second: 3 }
}
function clockUpdate() {
const { hour, minute, second } = calculateDiff()
setTime(hour, minute, second)
}
clockUpdate()
setInterval(clockUpdate, 1000)
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment