Reputation: 77
I have this function that disables the button after clicking it, how can I save the state in local storage.
cancelado: function() {
var x = document.getElementById("myBtn");
x.disabled = true;
}
Upvotes: 3
Views: 165
Reputation: 8722
Whenever you change the button's state, you need to update a flag in the local storage - you could even write a function that does both in one go, e.g.
function setButtonDisabled(state) {
// Update the button's state
document.getElementById("myBtn").disabled = state;
// Set the local storage flag to match
localStorage.setItem("myBtnState", state);
}
// Usage would be setButtonDisabled(true) to disable or
// setButtonDisabled(false) to enable
When you load the page, you then would need to get that state (if it exists), and update the button, e.g.
// On page load (or in whatever event creates the button)
window.addEventListener("load", ()=>{
// Read the saved state from local storage (if not yet saved, will be null)
let myBtnState = localStorage.getItem("myBtnState");
if (myBtnState != null) { // If a state has been saved...
// ...reset the state of the button from the saved state
document.getElementById("myBtn").disabled = myBtnState == "true";
}
});
Note that local storage can only store strings (technically DOMStrings), not booleans (or numbers, objects, functions, etc), so the value we pass in (a boolean value of true
or false
) will be automatically converted to "true"
or "false"
- hence we need to check if this value equals a string value of "true"
to convert it back to an actual boolean value.
You can read more about the local storage API at MDN.
I bet, however, that you have more than element that you want to save the state for. Additionally, this is a very "mechanical" solution to the problem. It would probably be better to save some sort of JSON object representing the state of the page, rather than the effects of that state.
For example, what is causing the button to be getting disabled? Lets say that it's because the user has entered a number that's too large in a form. In that case, it would be better to save the number, because then not only could we fill it back into the box, but also if no number is filled into the box, then the button shouldn't be greyed out. This also lets us change logic better - if we upped the maximum on allowed numbers, then users that come back to the page after entering numbers that used to be too small will still find the box greyed out, whereas if we had saved the number, we could perform the calculation again and realise that their number is now valid.
Upvotes: 1