I have developed a web page for the star ratings. I need to save the star value into local storage when the user clicks on stars and need to display that value on stars when the page reloads.
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>
Please help me to solve this problem. How can I use 'localStorage.setItem()' to set star values and how to display that star value when the page reloads?
well for localstorage you can use something like
localStorage.setItem('star', 'theStarClickedID');
and then you get it back with
var star = localStorage.getItem('star');
then you check the value of star and depending on that you put all lower to filledstar
EDIT: another thing, for this part
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");
}
}
i think you can do
for (i = 1; i <= parseInt(id); i++) {
document.getElementById(i).setAttribute("src", "./img/fillstar.png");
}
SECOND EDIT: what you asked for
<script>
load()
function load() {
var star = localStorage.getItem('star');;
for (i = 1; i <= parseInt(star); i++) {
document.getElementById(i).setAttribute("src", "./img/fillstar.png");
}
}
</script>