Here's how I'd do it:
HTML:
<ul class="responsive-review">
<li style="--rating-color:darkred">
<input type="radio" name="rating" id="rating-1" value="1" />
<label for="rating-1"></label>
</li>
<li style="--rating-color:orangered">
<input type="radio" name="rating" id="rating-2" value="2" />
<label for="rating-2"></label>
</li>
<li style="--rating-color:yellow">
<input type="radio" name="rating" id="rating-3" value="3" />
<label for="rating-3"></label>
</li>
<li style="--rating-color:yellowgreen">
<input type="radio" name="rating" id="rating-4" value="4" />
<label for="rating-4"></label>
</li>
<li style="--rating-color:darkgreen">
<input type="radio" name="rating" id="rating-5" value="5" />
<label for="rating-5"></label>
</li>
</ul>
CSS:
.responsive-review {
list-style: none;
display: inline-flex;
}
.responsive-review > li {
margin: 0 5px;
position: relative;
}
.responsive-review input[type='radio']{
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
opacity: 0;
}
.responsive-review label {
display: block;
width: 50px;
height: 40px;
background-color: #bbb;
}
.responsive-review input[type='radio']:checked + label{
background-color: var(--rating-color);
}
Javascript:
const updateReview = function(evt) {
const selectedLi = evt.currentTarget;
const ratingColor = getComputedStyle(selectedLi).getPropertyValue("--rating-color");
for (let li = selectedLi.previousElementSibling; li; li = li.previousElementSibling) {
const label = li.querySelector("label");
label.style.backgroundColor = ratingColor;
}
for (let li = selectedLi; li; li = li.nextElementSibling) {
const label = li.querySelector("label");
label.style.backgroundColor = null;
}
};
const lists = document.querySelectorAll(".responsive-review > li");
lists.forEach(li => li.addEventListener("click", updateReview));
Demo[
^]
The
<input type="radio">
handles selecting a single item from the list.
The CSS automatically assigns the correct background colour to the selected item, using CSS variables on the list items to define the colour for each.
You just need a little bit of Javascript to set the correct background colour on the previous list items, and clear the explicit background colour from the selected item and any following items.
You'll probably want to add some text to the labels for accessibility, possibly hidden for anything other than screen readers. And remember to check that your chosen colours work for colour-blind users.