Hi there,
this is my first topic, so sorry if i had made something wrong.
I have a problem, i need to save a button state, so after the reload of the webpage it should have the same state, as before. JavaScript ist new too me so i think i make something wrong, i try to solve this problem with localStorage, but it went wrong.
Here is the switch button, which overwritte the button text and change the background color. So i need that if i click on it and it turns from color 1 to color 2 and so on, that this state should be saved, so i can reload the page and the button have the last state. I thank you in advance.
html
<button id="letsgo">
lets go
</button>
<style> #letsgo { background: green; } </style>
javascript
main function:
<script>
onload = init;
function init() {
var onclick = changeContent();
var ltsg = document.getElementById("letsgo");
ltsg.addEventListener("click", onclick, true);
}
var state = localStorage.getItem("state");
function changeContent() {
var count = 0;
var next = function() {
switch(count) {
case 0:
// function click 1 here
document.getElementById("letsgo").style.backgroundColor = "red";
document.getElementById("letsgo").innerHTML = "stop";
break;
case 1:
// function click 2 here
document.getElementById("letsgo").style.backgroundColor = "green";
document.getElementById("letsgo").innerHTML = "lets go";
break;
}
if (count === 0)
{
localStorage.setItem("state", count);
count++;
}
else {
localStorage.setItem("state", count);
count = 0;
}
}
return next;
}
</script>
how i try to solve this problem:
<script>
onload = init;
function init() {
var onclick = changeContent();
var ltsg = document.getElementById("letsgo");
ltsg.addEventListener("click", onclick, true);
}
var state = localStorage.getItem("state");
var count = 0;
function saveit() {
if (state === 0) {
function changeContent() {
count = 0;
var next = function() {
switch(count) {
case 0:
// function click 1 here
document.getElementById("letsgo").style.backgroundColor = "red";
document.getElementById("letsgo").innerHTML = "stop";
break;
case 1:
// function click 2 here
document.getElementById("letsgo").style.backgroundColor = "green";
document.getElementById("letsgo").innerHTML = "lets go";
break;
}
if (count === 0)
{
localStorage.setItem("state", count);
count++;
}
else {
localStorage.setItem("state", count);
count = 0;
}
}
return next;
}
}
else {
function changeContent() {
count = 1;
var next = function() {
switch(count) {
case 1:
// function click 2 here
document.getElementById("letsgo").style.backgroundColor = "green";
document.getElementById("letsgo").innerHTML = "lets go";
break;
case 0:
// function click 1 here
document.getElementById("letsgo").style.backgroundColor = "red";
document.getElementById("letsgo").innerHTML = "stop";
break;
}
if (count == 1)
{
localStorage.setItem("state", count);
count = 0;
}
else {
localStorage.setItem("state", count);
count ++;
}
}
return next;
}
}
}
</script>