JSFiddle - React, Tailwind, and code Playground
HTML
Input:
<input type="text" id="input" value="January 01, 2020 14:00:00"/>
Timer: <span id="countup1"><span class="value_timer">00</span></span>
Errors: <span id="errors"></span>
CSS
span.digit {
background: black;
color: white;
padding: 1px 3px;
margin: 1px;
font-family: var(--mainFontFamily);
font-size: var(--mainFontSize);
}
JavaScript
// TIMER Styling START
function styleChars(targetEl) {
const val = targetEl.textContent;
const chars = val.split('');
targetEl.innerHTML = chars.map(c => `<span class="digit">${c}</span>`).join('');
}
const target = document.querySelector('.value_timer');
console.log(target);
styleChars(target);
// TIMER Styling END
// TIMER START
var timerDate = "January 01, 2020 14:00:00";
function setTimer() {
// Month Day, Year Hour:Minute:Second, id-of-element-container.
countUpFromTime(timerDate, 'countup1');
};
window.onload = setTimer();
function countUpFromTime(countFrom, id) {
const countDate = new Date(countFrom);
const errorDisplay = document.getElementById('errors');
const counterDisplay = document.getElementById(id);
if (isNaN(countDate.getTime())) {
errorDisplay.innerHTML = 'The input value is not a valid date!';
counterDisplay.innerHTML = '';
} else {
const now = new Date();
const timeDifference = (now.getTime() - countDate.getTime());
const value_timer = Math.floor(timeDifference / 1000 / 60 / 60);
counterDisplay.innerHTML = value_timer;
errorDisplay.innerHTML = '';
styleChars(counterDisplay); // Pass element to styling function.
}
const currentInputValue = document.getElementById('input').value;
clearTimeout(countUpFromTime.interval);
countUpFromTime.interval = setTimeout(function () {
countUpFromTime(currentInputValue, id);
}, 1000);
}
// TIMER END