
The stars-rating component is a customizable, easy-to-use 5-star rating system, built with vanilla JavaScript.
It has the ability to display average ratings and the total number of votes. This provides a simple way to gather user feedback through a simple click interface.
Once a user selects a rating, the component triggers an event, notifying the application of the new rating. After submission, the component becomes inactive to prevent multiple ratings from the same user.
How to use it:
1. Import the stars-rating as a module.
<script type="module" src="stars-rating.js"></script>
2. Insert the <stars-rating> element directly into your HTML and set initial values with the following attributes:
<stars-rating rating="4.3" count="123"></stars-rating>
3. Use an event listener to receive rating data. The following code snippet demonstrates how to capture and display the user’s rating:
document.body.querySelector("stars-rating").addEventListener("rating", getValue);
function getValue(evt) {
console.log(${evt.detail});
}4. You can also create the star rating component using JavaScript.
const stars = document.createElement("stars-rating");
stars.addEventListener("rating", getValue);
stars.id = "stars";
stars.rating = 4.3;
stars.count = 123;
document.querySelector("p").insertAdjacentElement("afterend", stars);
stars.beginRating();5. The star rating component can be fully styled using CSS variables and properties:
--rating-text-font: component font; --rating-stars-font: stars font; --rating-stars-color: stars color; --rating-btn-color: button color; --rating-btn-bg-color: button background color; --rating-btn-shadow: button box-shadow; --rating-tip-color: tip background color; --rating-tip-width: tip box width; --rating-tip-border: tip border; --rating-tip-shadow: tip box-shadow;
6. You can also target specific parts of the component using the following selectors:
- ::part(stars): the stars themselves
- ::part(rateBtn): the rate button
- ::part(rating): the rating number
- ::part(count): the count number
- ::part(tip): the tooltip container
- ::part(tip-text): the tooltip text
7. Customize tooltips for stars:
StarsRating.ratingLabels = ["Terrible", "Poor", "Fair", "Good", "Great"];
8. Change the button labels using:
StarsRating.ratingBtnLabels = ["Rate", "Send"];







