JSFiddle - React, Tailwind, and code Playground

by Prathameshsb

HTML

<h1>
Star rating for n no. of stars
</h1>
<div class="rating" id="rating-container"></div>
<div id="rated-message"></div>

CSS

.rating {
  font-size: 24px;
}

.star {
  cursor: pointer;
}

.star:hover,
.star.active {
  color: gold;
}

JavaScript

const totalStars = 7; // Change this number to set the total number of stars

const ratingContainer = document.getElementById('rating-container');
const ratedMessage = document.getElementById('rated-message');

function createStars() {
  for (let i = 1; i <= totalStars; i++) {
    const star = document.createElement('span');
    star.classList.add('star');
    star.innerHTML = '&#9733;';
    star.onclick = () => rate(i);
    ratingContainer.appendChild(star);
  }
}

function rate(star) {
  updateStars(star);
  showRatedMessage(star);
}

function updateStars(star) {
  const stars = document.querySelectorAll('.star');
  stars.forEach((s, index) => {
    s.classList.toggle('active', index < star);
  });
}

function showRatedMessage(star) {
  ratedMessage.textContent = `You rated this product ${star} stars!`;
}

createStars();