Interactive Rating Component with SASS & Vanilla JS

Solution retrospective
Any input is welcome, but specifically about the JS side please. Is there a more efficient way to achieve the same goal without having to repeat the for loop once more? Thanks ^^
Please log in to post a comment
Log in with GitHubCommunity feedback
- @elaineleung
Hi Jane XANE, here's what I did for my component:
For the HTML: I made my rating buttons into inputs, gave them a class of
.rating__btn
and a value of the score:<input type="button" class="rating__btn" value="1" />
For the CSS: I dreated a class
btn__is-selected
that changes the background to gray when the button is selectedFor the JS side, see below:
const [...scoreBtns] = document.querySelectorAll(".rating__btn"); let selected = null; // this keeps track of which rating was selected scoreBtns.map((btn) => { // add event listener to track which button is clicked btn.addEventListener("click", function (event) { selected = event.target.value; // remove the styling class from all buttons and then add it back to the selected one scoreBtns.forEach((btn) => { btn.classList.remove("btn__is-selected"); if (btn.getAttribute("value") === selected) { btn.classList.add("btn__is-selected"); } }); }); });
Marked as helpful
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