Web Component Dictionary v2.0 - 83 Components / 8 Categories / Bilingual / Live Preview
Live Demo | Buy
The star rating component is a staple of every product page. Here is how to build a fully functional, accessible version with minimal code.
The Core CSS Trick
.ef-star.hovered, .ef-star.selected { color: #f59e0b; }
.ef-star:hover { transform: scale(1.2); }
The JS Logic
stars.forEach((star, i) => {
star.addEventListener('mouseenter', () => updateDisplay(i+1, currentRating));
star.addEventListener('mouseleave', () => updateDisplay(0, currentRating));
star.addEventListener('click', () => {
currentRating = i+1;
updateDisplay(0, currentRating);
});
});
Accessibility
- Add
role="radiogroup"on the container - Add
role="radio"andaria-labelon each star - Support
EnterandSpacekeys for keyboard navigation
Key Pitfalls
- Always add
user-select: noneto prevent text selection on drag - Do not use native
input[type=radio]- native CSS styling is extremely difficult - Store current value in
data-ratingattribute for easy form submission
Top comments (0)