-
Notifications
You must be signed in to change notification settings - Fork 5
/
reviews.js
76 lines (65 loc) · 2.15 KB
/
reviews.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
let reviews;
let slideIndex = 0;
function loadStars(stars){
const calculatedStars = [];
for (let i = 0; i < Math.floor(stars); i++){
calculatedStars.push(`<img src="images/full-star.svg">`);
}
if(stars === 5){
return calculatedStars.map((item) => item).join('');
}
if(Number.isInteger(stars)){
for (let i = 0; i < 5 - stars; i++){
calculatedStars.push(`<img src="images/empty-star.svg">`);
}
} else {
calculatedStars.push(`<img src="images/half-star.svg">`);
for (let i = 0; i < 4 - Math.floor(stars); i++){
calculatedStars.push(`<img src="images/empty-star.svg">`);
}
}
return calculatedStars.map((item) => item).join('');
}
function loadReviews(review){
return `
<div class="review">
<div class="review__headshot">
<img src="${review.headshot}" alt="${review.name}">
</div>
<p class="review__name"><strong>${review.name}</strong></p>
<p class="review__location">${review.location}</p>
<div class="review__stars">${loadStars(review.stars)}</div>
<p class="review__body">${review.body}</p>
</div>
`;
}
function moveSlider(e){
if(e.currentTarget.id.includes('right')){
slideIndex === reviews.length - 1 ? (slideIndex = 0) : slideIndex++;
} else {
slideIndex === 0 ? (slideIndex = reviews.length - 1) : slideIndex--;
}
document.querySelector('.reviews').style.transform = `translate(${-100 * slideIndex}%)`;
}
// 1. Fetch the 'data' from our API
async function fetchReviews() {
await fetch('reviews.json')
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then((data) => {
reviews = data;
// 2. Parse the data and create the 'review' divs
document.querySelector('.reviews').innerHTML = data.map(loadReviews).join('');
})
.catch((error) => {
console.error('There has been a problem with your fetch operation:', error);
});
}
fetchReviews();
// 3. Add event listeners to move the slider left and right
document.querySelector('#arrow--right').addEventListener('click', moveSlider);
document.querySelector('#arrow--left').addEventListener('click', moveSlider);