There is no problem with one element. I need to make at least 10 buttons, and so that they do not depend on each other. That is, some buttons were with hidden text, and others with open text.
What is the best way to do this so that the code does not look like a freak?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<style>
#myid { display: none; }
</style>
<button onclick="onclickmyid()">Open</button><br><br><span id="myid">Hidden text</span>
<script>
var myid = document.getElementById('myid');
function onclickmyid() {
myid.style.display = (myid.style.display == 'block') ? '' : 'block';
localStorage.setItem('conceal', myid.style.display);
}
if(localStorage.getItem('conceal') == 'block') {
document.getElementById('myid').style.display = 'block';
}
</script>
</body>
</html>
Put all the persistent data you need into an array or an object, then serialize that (single) array or object into a single Local Storage key. Something along the lines of
const config = localStorage.config
? JSON.parse(localStorage.config)
: defaultConfig; // define defaultConfig earlier
cons saveConfig = () => localStorage.config = JSON.stringify(config);
// then, to save to the config when a change is made:
function onclickmyid() {
const newShow = myid.style.display === '';
config.myid = newShow;
updateUI();
saveConfig();
}
// and retrieve values on pageload:
const updateUI = () => {
myid.style.display = config.myid ? 'block' : '';
// etc for other elements
};
updateUI();
I'd also highly, highly recommend avoiding inline handlers, they're pretty universally considered to be quite terrible practice nowadays - attach listeners properly using JavaScript's addEventListener instead whenever possible.
For additional buttons, just add more properties to the config object, and toggle and access them in the click handlers.