At the moment, I have a script that automatically clicks on a random checkbox whenever the page loads or refreshes. Through localStorage, I can also view the value of the input assigned to the randomly selected checkbox.
However, I'm facing an issue where none of the checkboxes stay checked upon page load or refresh using localStorage and it has left me puzzled right now.
HTML
<div id="all-games">
<div>
<h2>Microsoft Xbox</h2>
<ul id="games" class="no-bullets">
<img src="./Game Covers/Microsoft/Microsoft Xbox/call of duty 3.png">
<li class="video-game"><label><input type="checkbox" value="cod-3" onchange="scrollToGame()"/></label>Call of Duty 3</li>
<!-- Other game checkboxes -->
</ul>
</div>
</div>
Javascript
<script>
const games = document.querySelectorAll(".video-game input[type=checkbox]:not(:checked)"); // select games that are currently not checked
const checkbox = Math.floor(Math.random() * games.length); // get a random index from 0 to games length
const scrolledGame = games[checkbox];
scrolledGame.click(); // click on the checkbox for the randomly selected game
const gameValue = scrolledGame.value;
function scrollToGame() {
scrolledGame.scrollIntoView({
behavior: "smooth"
});
};
if (scrolledGame.checked) {
localStorage.setItem('game title', gameValue); // title value of the selected checkbox via localStorage
scrolledGame.checked = true;
};
if (localStorage.getItem('game title') === gameValue) {
scrolledGame.checked = true;
console.log(scrolledGame.checked);
};
</script>