Toggle Problem with Star Rating System
I’m working on a star rating feature for my website and running into an issue. The stars work fine when you click them the first time, but they won’t reset when you click the same star again.
What should happen:
- Default state shows
-in the rating display - Clicking a star shows the rating text (like excellent, good, etc.)
- Clicking the same star again should reset back to
-
Current problem: The reset functionality isn’t working properly.
const ratingItems = document.querySelectorAll(".rating-star");
let currentRating = 0;
ratingItems.forEach(item => {
item.addEventListener("mouseenter", () => {
const starIndex = parseInt(item.getAttribute("data-rating"));
ratingItems.forEach((element, idx) => {
element.innerHTML = (idx < starIndex) ? "★" : "☆";
});
});
item.addEventListener("mouseleave", () => {
ratingItems.forEach((element, idx) => {
element.innerHTML = (idx < currentRating) ? "★" : "☆";
});
});
item.addEventListener("click", () => {
const starIndex = parseInt(item.getAttribute("data-rating"));
if (starIndex === currentRating) {
currentRating = 0;
return;
} else {
currentRating = starIndex;
}
ratingItems.forEach((element, idx) => {
element.innerHTML = (idx < currentRating) ? "★" : "☆";
});
updateRatingText(currentRating);
});
});
const displayElement = document.querySelector('.rating-display');
function updateRatingText(value) {
switch (value) {
case 0:
displayElement.textContent = '-';
break;
case 1:
displayElement.textContent = 'Terrible';
break;
case 2:
displayElement.textContent = 'Bad';
break;
case 3:
displayElement.textContent = 'Okay';
break;
case 4:
displayElement.textContent = 'Great';
break;
case 5:
displayElement.textContent = 'Amazing';
break;
}
}
<div class="user-rating">
<div class="rating-header">
<h3>Your Rating</h3>
</div>
<div class="rating-container">
<span class="rating-star" data-rating="1">☆</span>
<span class="rating-star" data-rating="2">☆</span>
<span class="rating-star" data-rating="3">☆</span>
<span class="rating-star" data-rating="4">☆</span>
<span class="rating-star" data-rating="5">☆</span>
</div>
<div class="rating-display">-</div>
</div>
Can anyone spot what I’m missing here?