Frontend dev project for a star rating system
I'm wondering if there if an easier way to go about this, specifically when using css to highlight all previous items in the list and if there's anything I can do to improve my javascript. However it does alll work. I'm not sure about the psuedo elements, i want feedback if i'm using the most efficent code.
https://codepen.io/Ziphour/pen/wvZovga
5 Replies
this is how i would do it
for this part
u can also just use ternary if u want but i think it looks more readable as it is
Thank you so much, I don't quite understand about you putting two arguments in the foreach loops and how it knew what was what?
but yeah this code is brilliant ty! man
the call back function of a forEach() can take two arguments. item and index.
item is mandatory and it represents the current item of an iterable (e.g array) on a particular iteration
index is optional and it represents the index of the current item that is being iterated
idk if that's what u mean
here we basically have a nested loop
a loop within a loop
1 loop is to add event listener to all stars and this runs only once as we r only going to loop through it once and add event listener to all stars
meanwhile the 2nd loop is within a call back function
the 2nd or inner loop pr inner forEach will run everytime a star is clicked
when a star is clicked
we start looping through all stars, from first to last
we know that if thr 4th sart is clicked then it's a 4 star rating / all the first 4 stars will be orange
now with the inner loop we'd start from the first star and start changing the src="" to orange start up until the start that has been clicked
rest will be set to a different src="" which is the grey one
u cab re factor the code like this
if this makes u understand better
Oh shit i get it
So can all array methods intake an element and index as their first and second argument?
and how come you don't need to assign an argument for the clicked value, how does the code know which index within the star array it refers to in this:
const callBack = (index) => {
// when clicked we loop through all the stars img
stars.forEach((img, idx) => {
// using the index we are setting all the stars starting from the first upto the one that's clicked to orange star
if (idx <= index) {
img.src = "https://iili.io/JWLiEQI.png";
}
// rest are set to grey star
else {
img.src = "https://iili.io/JWLi1hN.png;"
}
})
// using the index to select the appropriate reply
reply.textContent = replies[index];
}
oh shit is it because of () => callback(index) getting the index of the clicked star? and then the rest of the code says any index number less than or equal to is a gold star?!not all
like map or reduce i believe takes 3
better u just check yourself
yes