I have a toggle that show / hide a div section, everything works fine. So, i wrote a function in Js that save the toggle state after page refresh. The toggle state is stored correctly, but the section is always displayed, even if the toggle is saved to off. I don't understand where I'm wrong, someone help me ?
Fiddle: https://jsfiddle.net/snake93/s0rx4ube/4/
function save() {
var checkbox = document.getElementById("ck1");
localStorage.setItem("ck1", checkbox.checked);
}
var checked = JSON.parse(localStorage.getItem("ck1"));
document.getElementById("ck1").checked = checked;
$(document).ready(function(){
$(".switch input").on("change", function(e) {
const isOn = e.currentTarget.checked;
if (isOn) {
$(".hideme").show();
} else {
$(".hideme").hide();
}
});
});
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked .slider {
background-color: #2196F3;
}
input:focus .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
/*END OF TOGGLE SWITCH*/
.hideme {
padding:20px;
background: blue;
color: white;
font-weight: 800;
text-align: center;
}
<!-- jQuery -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<label >
<input type="checkbox" id="ck1" onchange="save()">
<span ></span>
</label>
<div >Please hide me, but bring me back later ;-)</div>
CodePudding user response:
It's because the only time the isOn state is checked is when the toggle switch is pressed. you need to check for the isOn state as soon as the document is ready. Like so.
function save() {
var checkbox = document.getElementById("ck1");
localStorage.setItem("ck1", JSON.stringify(checkbox.checked));
}
function isChecked(isOn) {
if (isOn === true) {
$(".hideme").show();
} else {
$(".hideme").hide();
}
}
//for loading
var checked = JSON.parse(localStorage.getItem("ck1"));
document.getElementById("ck1").checked = checked;
console.log(checked);
$(document).ready(function(){
isChecked(checked)
$(".switch input").on("change", function(e) {
const isOn = e.currentTarget.checked;
console.log(isOn)
isChecked(isOn);
});
});