@elaineleung
Posted
Hi Petru, I did this challenge a while ago and recently updated it with a different approach using radio buttons, but I think my old code might still help you out a bit. First, in your buttons, you'll want to add a value
for each button, like this:
<button class="btn" value="1" />1</button>
Here's roughly what the JS looked like:
const cardEl = document.getElementById("cardEl");
const scoreBtns = document.querySelectorAll(".btn");
let selected = null; // this will keep track of which button is pressed
scoreBtns.forEach((btn) => {
btn.addEventListener("click", (event) => {
event.preventDefault();
selected = btn.value;
selectScore(selected);
});
});
// this function handles what happens when the button is pressed
function selectScore(selected) {
scoreBtns.forEach((btn) => {
// first, remove all classes
btn.classList.remove("is-selected");
// checks button to see if value matches selected
if (btn.getAttribute("value") === selected) {
// adds class to button
btn.classList.add("is-selected");
}
});
}
In the CSS, you just make sure you write a rule for the button with the selected class and also the button hovered:
.btn:hover {
background-color: // btn color here;
}
.is-selected {
background-color: // selected btn background color here;
}
Hope this helps you out a bit! If you're interested in my radio button accessibility version (which is more complicated with labels and inputs being hidden and tabbed), you can check out my solution here: https://www.frontendmentor.io/solutions/responsive-interactive-rating-component-SeBo-aR4gB
Marked as helpful
@Petru14
Posted
@elaineleung thank you for your feedback, I will try to use the first solution, just in case it's not working I will check the second one. Thanks! 😀