-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
62 lines (49 loc) · 1.58 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
// Initial Ratings
const ratings = {
sony: 4.7,
samsung: 3.4,
vizio: 2.3,
panasonic: 3.6,
phillips: 4.1
}
// Total Stars
const starsTotal = 5;
// Run getRatings when DOM loads
document.addEventListener('DOMContentLoaded', getRatings);
// Form Elements
const productSelect = document.getElementById('product-select');
const ratingControl = document.getElementById('rating-control');
// Init product
let product;
// Product select change
productSelect.addEventListener('change', (e) => {
product = e.target.value;
// Enable rating control
ratingControl.disabled = false;
ratingControl.value = ratings[product];
});
// Rating control change
ratingControl.addEventListener('blur', (e) => {
const rating = e.target.value;
// Make sure 5 or under
if (rating > 5) {
alert('Please rate 1 - 5');
return;
}
// Change rating
ratings[product] = rating;
getRatings();
});
// Get ratings
function getRatings() {
for (let rating in ratings) {
// Get percentage
const starPercentage = (ratings[rating] / starsTotal) * 100;
// Round to nearest 10
const starPercentageRounded = `${Math.round(starPercentage / 10) * 10}%`;
// Set width of stars-inner to percentage
document.querySelector(`.${rating} .stars-inner`).style.width = starPercentageRounded;
// Add number rating
document.querySelector(`.${rating} .number-rating`).innerHTML = ratings[rating];
}
}