-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathratingscript.js
More file actions
76 lines (55 loc) · 2.06 KB
/
ratingscript.js
File metadata and controls
76 lines (55 loc) · 2.06 KB
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
// Access all span elements (such as the star) in a variable
let stars = document.querySelectorAll(".rating span");
// Access all div elements that have the class of ratings.
let foods = document.querySelectorAll(".rating");
// creating an empty array ratings
let ratings = [];
// loop through the stars
for(let star of stars){
star.addEventListener("click", function(){
//store all elements that involve the rating
let children = star.parentElement.children;
// for every star clicked it turns false to prevent double rating
for(let child of children){
if(child.getAttribute("data-clicked")){
return false;
}
}
// Everytime we click on a star we make a data set and make it true when its clicked on.
this.setAttribute("data-clicked", "true");
// get the data rating value
let rating = this.dataset.rating;
// fetch the food id
let foodId = this.parentElement.dataset.foodid;
// fetch food name
let foodName = this.parentElement.dataset.foodname;
console.log(rating, foodName, foodId);
// create a data table that will hold the rating number and the FoodItem Id
let data = {
"stars": rating,
"food-Id": foodId,
"food-Name": foodName
}
// inserting the data object within the empty array
ratings.push(data);
// storing it within local storage
localStorage.setItem("ratings", JSON.stringify(rating, foodName))
});
}
// Fetch the ratings of the Food items
if(localStorage.getItem("rating")){
ratings = JSON.parse(localStorage.getItem("rating"));
foodName = JSON.parse(localStorage.getItem("foodName"));
// loop throught the ratings array
for (let rating of ratings){
// loop through every food id in the page
for (let food of foods){
if(ratings["foodId"] == food.dataset.foodId){
let reversedStars = Array.from(food.children).reverse();
// fetch the number of stars given to the food item
let index = parseInt(rating["stars"]) - 1;
reversedStars[index].setAttribute("data-clicked", "true");
}
}
}
}