I have a checkbox that if I select it, my container is hidden and if I deselect it, the container is shown again.
I’m trying to save the state in localstorage. So if the page refreshes or changes, the checkbox maintains its state
Sorry if I don’t explain myself well, how could I achieve this? Thank you
My code so far
<label class="switch">
<input type="checkbox" id="myToggle">
<span class="slider round"></span>
</label>
<div id="main-container">
HELLO
</div>
<script>
const checkbox = document.getElementById('myToggle')
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
const a = localStorage.setItem('my_variable', 'activated');
} else {
localStorage.removeItem('my_variable');
}
})
function hideshowContainer(){
if( a == 'activated'){
document.getElementById('main-container').style.display="none";
}else{
document.getElementById('main-container').style.display="block";
}
}
</script>
2
Answers
Try this code
[https://jsfiddle.net/f92awop1/]
Your code is most of the way there. You just need to also read the state of the localStorage value when the page next loads, like this:
Here’s a full working example in jsFiddle, as SO snippets are sandboxed and cannot access localStorage.