I have developed a web page for the star ratings. I need to unselect the stars if the user clicks twice on the same star, how to unselect all the star rating values? that means if the user clicks on 3 stars for the rating and again click on the 3rd star how to disappear all the rating stars value?
This is what I tried
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="manifest" href="manifest.json">
</head>
<body>
<h1>This is Home page</h1>
<p>This is a testing page for rating.</p>
<div>
<img onClick="rate()" class="star" id="1" src="./img/star.png" />
<img onClick="rate()" class="star" id="2" src="./img/star.png" />
<img onClick="rate()" class="star" id="3" src="./img/star.png" />
<img onClick="rate()" class="star" id="4" src="./img/star.png" />
<img onClick="rate()" class="star" id="5" src="./img/star.png" />
</div>
<div>
<img onClick="rate1()" class="star" id="6" src="./img/star.png" />
<img onClick="rate1()" class="star" id="7" src="./img/star.png" />
<img onClick="rate1()" class="star" id="8" src="./img/star.png" />
<img onClick="rate1()" class="star" id="9" src="./img/star.png" />
<img onClick="rate1()" class="star" id="10" src="./img/star.png" />
</div>
</body>
</html>
<script>
function rate() {
const { id } = event.target;
var i;
for (i = 1; i <= 5; i++) {
if (i <= parseInt(id)) {
document.getElementById(i).setAttribute("src", "./img/fillstar.png");
} else {
document.getElementById(i).setAttribute("src", "./img/star.png");
}
}
}
function rate1() {
const { id } = event.target;
var i;
for (i = 6; i <= 10; i++) {
if (i <= parseInt(id)) {
document.getElementById(i).setAttribute("src", "./img/fillstar.png");
} else {
document.getElementById(i).setAttribute("src", "./img/star.png");
}
}
}
</script>
You can dynamically add class to every rated star to indicate if it is filled or not (e.g, add class name
filledto every rated star). Then, on every click check if the element ofevent.targetcontains the classfilled. If so, call your functions and in addition, remove allfilledclasses (unrate). If not, addfilledclass to every relevant star (rate).To dynamically toggle (add or remove) a class to an element, you can use
element.classList.toggle("className").see: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
code example (similar to yours): https://stackblitz.com/edit/star-rating-demo?file=index.html