I'm a beginner, and I simply code for fun and make little simple projects. This month I'm trying to make a horse racing "game". This game is the first project that uses local storage, so I'm not exactly familiar on how to code it. I got a basic understanding of it thanks to w3 schools and MDN, but there's still plenty of bugs. The one that bugs me the most is the name changing function. In my code, you can click a button, and a prompt will ask you for a new name for the horse. Then, the screen displays it, and the value is saved to a variable and local storage. However, when I reload the page, the name is not changed, and the screen still displays the default name. Is there any way to fix this?
var horse = {
energy: false,
name: false,
speed: false,
money: false,
busy: false,
hayBale: false,
};
//these are my LS checks and loads...
if(localStorage.getItem("energy") === false) {
localStorage.setItem("energy", 100);
}
if(localStorage.getItem("name") === false) {
localStorage.setItem("name", "Give your horse a name!");
}
if(localStorage.getItem("speed") === false) {
localStorage.setItem("speed", 0);
}
if(localStorage.getItem("busy") === false) {
localStorage.setItem("busy", 0);
}
if(localStorage.getItem("hayBale") === false) {
localStorage.setItem("hayBale", 0);
}
if(localStorage.getItem("money") === false) {
localStorage.setItem("money", 0);
}
horse.name = localStorage.getItem("name");
horse.speed = parseFloat(localStorage.getItem("speed"), 10);
horse.busy = parseInt(localStorage.getItem("busy"), 10);
horse.hayBale = parseInt(localStorage.getItem("hayBale"), 10);
horse.money = parseInt(localStorage.getItem("money"), 10);
horse.energy = parseInt(localStorage.getItem("energy"), 10);
//and this is my name changing function.
$("#horseName").click(function() {
var newName = prompt("What do you want to rename your horse to? (the name is changable at any time)");
if(newName !== "" && newName !== false) {
alert("Success! Your horse is now named '" + newName + "'!");
document.getElementById("horseName").innerHTML = newName;
horse.name = newName;
localStorage.setItem("name", newName);
} else {
alert("You didn't enter a name!");
}
});