JSFiddle - React, Tailwind, and code Playground
by Prathameshsb
HTML
<div class='stars'>
</div>
CSS
.noOfStars:hover,
.noOfStars.active {
color: gold;
}
JavaScript
const totalStar = 7;
let selectedStar = 0;
const getStarsEle = document.querySelector('.stars');
function createStars() {
for(let i = 1; i <= totalStar; i++) {
const starSpan = document.createElement('span');
starSpan.innerHTML = '★';
starSpan.classList.add('noOfStars');
starSpan.onclick = () => rating(i);
getStarsEle.appendChild(starSpan);
}
}
function rating(i) {
selectedStar = i;
updateStar(i);
}
function updateStar(i) {
const noOfStars = document.querySelectorAll('.noOfStars');
noOfStars.forEach((val, index) => {
val.classList.toggle('active', index < i);
})
}
createStars();