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>
>Solution :
Try this code
[https://jsfiddle.net/f92awop1/]
<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');
// Load the checkbox state from localStorage on page load
const savedState = localStorage.getItem('my_variable');
if (savedState === 'activated') {
checkbox.checked = true;
hideshowContainer();
}
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
localStorage.setItem('my_variable', 'activated');
} else {
localStorage.removeItem('my_variable');
}
hideshowContainer();
})
function hideshowContainer() {
const currentState = localStorage.getItem('my_variable');
if (currentState === 'activated') {
document.getElementById('main-container').style.display = "none";
} else {
document.getElementById('main-container').style.display = "block";
}
}
</script>