Rating Component - HTML, CSS and JS

Solution retrospective
Hey everyone! I just have two problems. My JS works, but the code itself is very repetitive I notice.(I don't know any JS libraries/frameworks yet) If someone has a way for me to simplify my code, I'll greatly appreciate it! My next problem is with the functionality of the rating buttons. So when I click on a number, it does what it's supposed to, but when I click on another number, they both turn the same color...Now this obviously isn't supposed to be happening, but I couldn't figure the JS out for it not to be repetitive, so again, I'll be more than happy if someone could help me with that! Overall, I'm hoping to get some feedback on the design itself, the HTML/CSS I used. Would anyone do anything different or more efficient to what I did (specifically for the HTML and CSS portion)
Please log in to post a comment
Log in with GitHubCommunity feedback
- @remyboire
Hi @jplawrence ! This looks great, really well done ! Here is what I personnaly wrote :
buttons.forEach((element) => { element.addEventListener('click', () => { buttons.forEach((element) => { element.classList.remove('selected') }) element.classList.add('selected') }) })
This is not as repetitive as your method, plus, adding and removing a class is easier to maintain as colors and styles remains in the CSS file.Marked as helpful - @danyrszz
i have problems with my html semantics but i can help with the JS part:
you can add the same class to each one of your li elements, then do a querySelectorAll to assign each one of them to an array, then you can do two things: either add an eventlistener to the ul element (container) to manage each one of the li clicks, or add an event listener to each one of li elements, so that when you click you can have the exact clicked element and you'll be able to do something like "event.target.classList.add("selected") where selected will have the desired background color, then to remove the previous selected element you can at each click traverse the array and do something like "event.target.classList.remove("selected") for each li element.
This way you write the event just once and you can add as many elements as you like without having to touch the js.
That's kinda the way i did it, hope i made myself clear
Marked as helpful - @Kl3va
You can start by doing a little research on event delegation and propagation. Then, use only one function to handle the change of color by assigning an active class when clicked other than calling different functions to do the exact same thing.
Join our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord