-
Notifications
You must be signed in to change notification settings - Fork 7
/
StarRating.js
68 lines (51 loc) · 1.65 KB
/
StarRating.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
class StarRating extends HTMLElement {
get value () {
return this.getAttribute('value') || 0;
}
set value (val) {
this.setAttribute('value', val);
this.highlight(this.value - 1);
}
get number () {
return this.getAttribute('number') || 5;
}
set number (val) {
this.setAttribute('number', val);
this.stars = [];
while (this.firstChild) {
this.removeChild(this.firstChild);
}
for (let i = 0; i < this.number; i++) {
let s = document.createElement('div');
s.className = 'star';
this.appendChild(s);
this.stars.push(s);
}
this.value = this.value;
}
highlight (index) {
this.stars.forEach((star, i) => {
star.classList.toggle('full', i <= index);
});
}
constructor () {
super();
this.number = this.number;
this.addEventListener('mousemove', e => {
let box = this.getBoundingClientRect(),
starIndex = Math.floor((e.pageX - box.left) / box.width * this.stars.length);
this.highlight(starIndex);
});
this.addEventListener('mouseout', () => {
this.value = this.value;
});
this.addEventListener('click', e => {
let box = this.getBoundingClientRect(),
starIndex = Math.floor((e.pageX - box.left) / box.width * this.stars.length);
this.value = starIndex + 1;
let rateEvent = new Event('rate');
this.dispatchEvent(rateEvent);
});
}
}
customElements.define('x-star-rating', StarRating);