-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraf.js
112 lines (91 loc) · 2.5 KB
/
graf.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
class Graph {
/*
options
transition: 1s //time
animation: true //true or false, if there should be a animation
delay: 0 //time in millisecs, after the delay the animation will autoplay
*/
constructor(parent, options = {}) {
this.parent = parent;
this.duration = options.transition ? options.transition : "1s";
this.animation = options.animation ? options.animation : true;
this.delay = options.delay ? options.delay : null;
this.oldMax = this.max; //the old max
//functions
this.play = this.play.bind(this);
this.setTransition();
if (this.delay !== null) {
setTimeout(this.play, this.delay);
}
}
//henter alle elementer inni med class graf
get children() {
return this.parent.querySelectorAll(".graf");
}
//finner ut om den står eller ikke
get direction() {
return this.parent.classList.contains("standing");
}
//finner den største verdien
get max() {
let max = -Infinity;
this.children.forEach(elem => {
const value = Number(elem.getAttribute("data-value"));
if (value > max) {
max = value;
}
});
return max;
}
//return percentage
percentageOfMax(value) {
return (value * 100) / this.oldMax;
}
//kjører en funksjon på alle elementer med class graf
mapChildren(func) {
this.children.forEach(func);
}
//sets the transition of the children
setTransition() {
if (this.animation) {
this.mapChildren(elem => {
this.setOneTransition(elem);
});
}
}
//set animation of one
setOneTransition(elem) {
elem.style.transition = this.duration;
this.setSize(elem, 0);
}
//adds a new child
add(value, classes = [], text = "") {
const newChild = document.createElement("div");
classes.forEach(elem => {
newChild.classList.add(elem);
});
newChild.innerHTML = text;
newChild.setAttribute("data-value", value);
this.parent.appendChild(newChild);
this.setOneTransition(newChild);
if (value > this.oldMax) {
this.oldMax = this.max;
}
setTimeout(this.play, 1);
}
//plays the animations
play() {
this.mapChildren(elem => {
const value = Number(elem.getAttribute("data-value"));
this.setSize(elem, value);
});
}
//sets width/heigt of element
setSize(elem, value) {
if (!this.direction) {
elem.style.width = this.percentageOfMax(value) + "%";
} else {
elem.style.height = this.percentageOfMax(value) + "%";
}
}
} //end of class