-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclock.js
82 lines (70 loc) · 1.97 KB
/
clock.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
window.addEventListener("DOMContentLoaded",() => {
const clock = new BouncyBlockClock(".clock");
});
class BouncyBlockClock {
constructor(qs) {
this.el = document.querySelector(qs);
this.time = { a: [], b: [] };
this.rollClass = "clock__block--bounce";
this.digitsTimeout = null;
this.rollTimeout = null;
this.mod = 0 * 60 * 1000;
this.loop();
}
animateDigits() {
const groups = this.el.querySelectorAll("[data-time-group]");
Array.from(groups).forEach((group,i) => {
const { a, b } = this.time;
if (a[i] !== b[i]) group.classList.add(this.rollClass);
});
clearTimeout(this.rollTimeout);
this.rollTimeout = setTimeout(this.removeAnimations.bind(this),900);
}
displayTime() {
// screen reader time
const timeDigits = [...this.time.b];
const ap = timeDigits.pop();
this.el.ariaLabel = `${timeDigits.join(":")} ${ap}`;
// displayed time
Object.keys(this.time).forEach(letter => {
const letterEls = this.el.querySelectorAll(`[data-time="${letter}"]`);
Array.from(letterEls).forEach((el,i) => {
el.textContent = this.time[letter][i];
});
});
}
loop() {
this.updateTime();
this.displayTime();
this.animateDigits();
this.tick();
}
removeAnimations() {
const groups = this.el.querySelectorAll("[data-time-group]");
Array.from(groups).forEach(group => {
group.classList.remove(this.rollClass);
});
}
tick() {
clearTimeout(this.digitsTimeout);
this.digitsTimeout = setTimeout(this.loop.bind(this),1e3);
}
updateTime() {
const rawDate = new Date();
const date = new Date(Math.ceil(rawDate.getTime() / 1e3) * 1e3 + this.mod);
let h = date.getHours();
const m = date.getMinutes();
const s = date.getSeconds();
const ap = h < 12 ? "AM" : "PM";
if (h === 0) h = 12;
if (h > 12) h -= 12;
this.time.a = [...this.time.b];
this.time.b = [
(h < 10 ? `0${h}` : `${h}`),
(m < 10 ? `0${m}` : `${m}`),
(s < 10 ? `0${s}` : `${s}`),
ap
];
if (!this.time.a.length) this.time.a = [...this.time.b];
}
}