forked from RDjarbeng/countdown
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
239 lines (207 loc) · 7.34 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
class Clock {
constructor(endDate) {
// expecting a date object
this.setEndDate(endDate)
this.countDown();
}
setEndDate(endDate) {
//set endDate to end of year
// todo: check endDate for validity as date
this.endDate = endDate ||new Date(`Jan 1, ${new Date().getFullYear() + 1} 00:00:00`)
}
countDown() {
// Set the date we're counting down to
let countDownDate = this.endDate.getTime();
let now = new Date().getTime();
var distance = countDownDate - now;
// account for case of the countdown being reached, reset
if (distance >= 0) {
// Time calculations for days, hours, minutes and seconds
this.calculateTimeValues(distance)
} else {
// clear date values
this.resetMethod();
}
}
resetMethod(){
this.clearCounter();
}
calculateTimeValues(distance){
this.days = Math.floor(distance / (1000 * 60 * 60 * 24));
this.hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
this.minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
this.seconds = Math.floor((distance % (1000 * 60)) / 1000);
}
countDays() {
//account for leap year
this.dayLength = ((this.endDate.getFullYear() % 4 != 0) ? 365 : 366)
return this.dayLength - this.days
}
clearCounter(){
this.days=this.hours=this.minutes=this.seconds=0;
}
}
class NewYearClock extends Clock{
resetMethod(){
//reset to New Year's for default
this.setEndDate()
}
}
// DOM nodes
let dayCount = document.getElementById("countDay");
const animatedCountDuration = 800;
const body = document.body;
var dayNumber = document.getElementById('day-num');
var hourNumber = document.getElementById("hour-num");
var minNumber = document.getElementById("min-num");
var secNumber = document.getElementById("sec-num");
var dueDate = document.getElementById('dueDate');
//to stop the clock
let intervalID;
let customClockMovement = false;
let dayClock = new NewYearClock();
// Initialize default Clock class
// var myclock = new NewYearClock();
var myclock = setMainClock();
var myclock = setMainClock();
setInnerHtmlForNotNull(dueDate, `Due: ${myclock.endDate.getDate() + ' ' + myclock.endDate.toLocaleString('default', { month: 'long' }) + ', ' + myclock.endDate.getFullYear()}`)
var customClock;
function setMainClock() {
let mainclock = localStorage.getItem('mainClock');
if (mainclock !== null && mainclock != undefined) { //countdown set to main
mainclock = JSON.parse(mainclock)
myclock = new Clock(new Date(mainclock.date));
setMainText(mainclock.text)
}
return myclock || new NewYearClock();
}
function setMainText(countdownText) {
const textDisplay = document.getElementById('countdown-text');
setInnerHtmlForNotNull(textDisplay, countdownText)
}
async function waitForAnimation(clock, domElements, duration) {
await stepIncreaseAndStart(clock || myclock, domElements, duration || animatedCountDuration)
startClock(clock || myclock, domElements);
}
function startClock(clock, { dayNumber, hourNumber, minNumber, secNumber }) {
intervalID = setInterval(() => { startTime(clock, { dayNumber, hourNumber, minNumber, secNumber }); }, 500);
}
function startTime(clock, { dayNumber, hourNumber, minNumber, secNumber }) {
// console.log(clock);
updateDisplay(clock, dayNumber, hourNumber, minNumber, secNumber);
setInnerHtmlForNotNull(dayCount, dayClock.countDays());
if (customClockMovement) {
updateDisplay(customClock, customDayNumber, customHourNumber, customMinNumber, customSecNumber);
}
}
// add zero in front of numbers < 10
function addZeros(time) {
if (time < 10) {
time = "0" + time;
}
return time;
}
function updateDisplay(counter, dayDisplay, hourDisplay, minDisplay, secDisplay) {
counter.countDown();
let d = counter.days
let h = counter.hours
let m = counter.minutes
let s = counter.seconds
d = addZeros(d);
h = addZeros(h);
m = addZeros(m);
s = addZeros(s);
setInnerHtmlForNotNull(dayDisplay, `${d}`);
setInnerHtmlForNotNull(hourDisplay, `${h}`);
setInnerHtmlForNotNull(minDisplay, `${m}`);
setInnerHtmlForNotNull(secDisplay, `${s}`);
}
/**
* Listens for a user input for date element
*/
function listenForDate() {
const input = this.value;
// console.log(input, 'run');
if (input != '') {
customClock = new Clock(new Date(input));
displayClockRow();
// do the fast countdown
// set speed faster when day of the year is greater
// todo: change to animateValue
stepIncreaseAndStart(customClock, { customDayNumber, customHourNumber, customMinNumber, customSecNumber }, (365 - customClock.days < 100) ? 365 - customClock.days : 70);
}
}
function displayClockRow() {
let customRow = document.getElementById("customDisplay");
// show row
customRow.style.display = 'block';
}
/* //restart the clock
function restartTime() {
if (customClockMovement) {
return;
} else {
startClock();
}
}
*/
//stop the clock
function stopClock() {
clearTimeout(intervalID);
customClockMovement = false;
}
//for the animated Countdown
function animateValue(domElement, start, end, duration) {
let startTimestamp = null;
const step = (timestamp) => {
if (!startTimestamp) startTimestamp = timestamp;
const progress = Math.min((timestamp - startTimestamp) / duration, 1);
setInnerHtmlForNotNull(domElement, addZeros(Math.floor(progress * (end - start) + start)))
if (progress < 1) {
window.requestAnimationFrame(step);
// animationComplete = false;
}
};
window.requestAnimationFrame(step);
}
async function stepIncreaseAndStart(clockElement, domElements, speed = 50, start_num = 0) {
animateValue(domElements.dayNumber, start_num, clockElement.days, speed);
animateValue(domElements.hourNumber, start_num, clockElement.hours, speed);
animateValue(domElements.minNumber, start_num, clockElement.minutes, speed);
animateValue(domElements.secNumber, start_num, clockElement.seconds, speed);
}
function addWhatappEventHandler() {
let whatsappIcon = document.getElementById('sendWhatsappButton');
if (whatsappIcon) {
whatsappIcon.addEventListener('click', exportToWhatsapp);
}
}
function exportToWhatsapp() {
let dayNum = dayCount.innerText;
window.open(`whatsapp://send?text= Day ${dayNum || 'rcountdown'}/365`);
}
function setInnerHtmlForNotNull(element, value){
if(element)//check for null
element.innerHTML = value;
}
try {
//show day value before animation runs
setInnerHtmlForNotNull(dayCount, dayClock.countDays());
// startTime();
waitForAnimation(myclock, { dayNumber, hourNumber, minNumber, secNumber }, animatedCountDuration);
addWhatappEventHandler();
// as;
} catch (error) {
errorHandler("Error in clock");
console.log(error);
}
// service worker
if('serviceWorker' in navigator){
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js')
.then( (reg)=>{
console.log('service worker registered', reg)
})
.catch((err)=> console.log('Service worker not registered', err));
});
}