-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcount-up.js
79 lines (72 loc) · 2.59 KB
/
count-up.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
if (!customElements.get('count-up')) {
class CountUp extends HTMLElement {
constructor() {
super();
this.settings = {
min: 0,
max: 100,
step: 1,
speed: 1,
infinite: true
}
}
connectedCallback() {
this.init();
}
init() {
if (this.classList.contains("count-up-init")) return;
var self = this,
data = this.datasetToObject(this.dataset);
Object.assign(this.settings, data);
this.classList.add('count-up-init');
if ("IntersectionObserver" in window) {
let counterObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
self.renderCounter();
self.classList.add('inView');
if(!data.infinite) counterObserver.unobserve(entry.target);
}else{
self.classList.remove('inView');
}
});
});
counterObserver.observe(self);
} else {
self.renderCounter();
}
}
datasetToObject(dataset) {
return JSON.parse(JSON.stringify(dataset), (key, value) => {
if (value === "null") return null;
if (value === "true") return true;
if (value === "false") return false;
if (!isNaN(value)) return Number(value);
try {
return JSON.parse(value);
} catch (e) {
return value;
}
});
}
renderCounter(counter){
var self = this,
min = this.settings.min,
max = this.settings.max,
step = this.settings.step,
speed = this.settings.speed,
counter = counter || min,
element = this.querySelector('.counter');
counter = counter + step;
if (counter <= max) {
element.innerHTML = counter.toString();
setTimeout(function(){
self.renderCounter(counter);
}, speed)
}else{
element.innerHTML = max.toString();
}
}
}
customElements.define("count-up", CountUp);
}