How to Create a 5-Star Rating System in JavaScript?

Estimated read time 2 min read

To create a 5-star rating system in JavaScript, you can follow these steps:

  1. Create the HTML structure for the star rating system, using input elements with type="radio":
<div class="rating">
  <input type="radio" id="star5" name="rating" value="5" />
  <label for="star5">5 stars</label>
  <input type="radio" id="star4" name="rating" value="4" />
  <label for="star4">4 stars</label>
  <input type="radio" id="star3" name="rating" value="3" />
  <label for="star3">3 stars</label>
  <input type="radio" id="star2" name="rating" value="2" />
  <label for="star2">2 stars</label>
  <input type="radio" id="star1" name="rating" value="1" />
  <label for="star1">1 star</label>
  1. Use CSS to style the stars and add a visual representation of the selected rating:
.rating {
  display: inline-block;
  position: relative;
  height: 50px;
  line-height: 50px;
  font-size: 50px;

.rating label {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  cursor: pointer;

.rating label:last-child {
  position: static;

.rating input {
  display: none;

.rating label:before {
  content: "\f005";
  font-family: FontAwesome;
  display: inline-block;
  color: #ddd;

.rating .half:before {
  content: "\f089";
  position: absolute;

.rating input:checked ~ label,
.rating:not(:checked) label:hover,
.rating:not(:checked) label:hover ~ label {
  color: #ffd700;

.rating input:checked + label:before {
  content: "\f005";
  position: absolute;
  color: #ffd700;
  transition: color 0.25s;
  1. Use JavaScript to add functionality to the rating system, such as getting the selected rating, submitting the rating, etc.:
let ratingInputs = document.querySelectorAll('.rating input');

for (let i = 0; i < ratingInputs.length; i++) {
  ratingInputs[i].addEventListener('click', function () {
    let ratingValue = this.value;
    console.log("Selected rating: " + ratingValue);

This code will create a 5-star rating system that allows the user to select a rating by clicking on the stars. The selected rating will be logged to the console. You can modify this code to suit your needs, for example by submitting the rating to a server or displaying the average rating.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply