-
Notifications
You must be signed in to change notification settings - Fork 1
/
script.js
87 lines (70 loc) · 2.37 KB
/
script.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
// navbar fixed
window.onscroll = function () {
const header = document.querySelector('header');
const fixedNav = header.offsetTop;
if (window.pageYOffset > fixedNav) {
header.classList.add('navbar-fixed');
} else {
header.classList.remove('navbar-fixed');
}
};
// hamburger
const hamburger = document.querySelector('#hamburger');
const navMenu = document.querySelector('#nav-menu');
hamburger.addEventListener('click', function () {
hamburger.classList.toggle('hamburger-active');
navMenu.classList.toggle('hidden');
});
window.addEventListener("DOMContentLoaded",() => {
const fr = new FaceRating("#face-rating");
});
class FaceRating {
constructor(qs) {
this.input = document.querySelector(qs);
this.input?.addEventListener("input",this.update.bind(this));
this.face = this.input?.previousElementSibling;
this.update();
}
update(e) {
let value = this.input.defaultValue;
// when manually set
if (e) value = e.target?.value;
// when initiated
else this.input.value = value;
const min = this.input.min || 0;
const max = this.input.max || 100;
const percentRaw = (value - min) / (max - min) * 100;
const percent = +percentRaw.toFixed(2);
this.input?.style.setProperty("--percent",`${percent}%`);
// face and range fill colors
const maxHue = 120;
const hueExtend = 30;
const hue = Math.round(maxHue * percent / 100);
let hue2 = hue - hueExtend;
if (hue2 < 0) hue2 += 360;
const hues = [hue,hue2];
hues.forEach((h,i) => {
this.face?.style.setProperty(`--face-hue${i + 1}`,h);
});
this.input?.style.setProperty("--input-hue",hue);
// emotions
const duration = 1;
const delay = -(duration * 0.99) * percent / 100;
const parts = ["right","left","mouth-lower","mouth-upper"];
parts.forEach(p => {
const el = this.face?.querySelector(`[data-${p}]`);
el?.style.setProperty(`--delay-${p}`,`${delay}s`);
});
// aria label
const faces = [
"Sad face",
"Slightly sad face",
"Straight face",
"Slightly happy face",
"Happy face"
];
let faceIndex = Math.floor(faces.length * percent / 100);
if (faceIndex === faces.length) --faceIndex;
this.face?.setAttribute("aria-label",faces[faceIndex]);
}
}