-
Notifications
You must be signed in to change notification settings - Fork 0
/
StarRater.js
84 lines (61 loc) · 1.81 KB
/
StarRater.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
class StarRater extends HTMLElement {
constructor() {
super();
this.build();
}
build() {
const shadow = this.attachShadow({ mode: 'open' });
shadow.appendChild(this.styles());
const rater = this.createRater();
this.stars = this.createStars();
this.stars.forEach(star => rater.appendChild(star));
this.resetRating();
shadow.appendChild(rater);
}
createRater() {
const rater = document.createElement('div');
rater.classList.add('star-rater');
rater.addEventListener('mouseout', this.resetRating.bind(this));
return rater;
}
createStars() {
const createStar = (_, i) => {
const id = Number(i) + 1;
const star = document.createElement('span');
star.classList.add('star');
star.setAttribute('data-value', id);
star.innerHTML = '★';
star.addEventListener('click', this.setRating.bind(this));
star.addEventListener('mouseover', this.ratingHover.bind(this));
return star;
};
return Array.from({ length: 5 }, createStar);
}
ratingHover(event) {
this.currentRatingValue = event.currentTarget.getAttribute('data-value');
this.highlightRating();
}
highlightRating() {
this.stars.forEach(star => {
star.style.color = this.currentRatingValue >= star.getAttribute('data-value') ? '#5E3BE0' : 'gray';
});
}
resetRating() {
this.currentRatingValue = this.getAttribute('data-rating') || 0;
this.highlightRating();
}
setRating(event) {
this.setAttribute('data-rating', event.currentTarget.getAttribute('data-value'));
}
styles() {
const style = document.createElement('style');
style.textContent = `
.star {
font-size: 5rem;
color: gray;
cursor: pointer;
}`;
return style;
}
}
customElements.define('star-rater', StarRater);