By pressing .trigger
the hidden
class is toggled to show/hide the .box
. I am trying to use localStorage
to remember the last state of the .box
i.e whether it has the hidden class or not.
How do I store whether each .box
has class hidden
, and then deliver the last selected state on page reload?
https://codepen.io/moofawsaw/pen/ExNPNyy
$(".box").toggleClass(localStorage.toggled);
$(document).ready(function() {
$(".trigger").on("click", function() {
var $this = $(this).closest(".item").find(".box");
if (localStorage.toggled != "hidden") {
$this.toggleClass("hidden", true);
localStorage.toggled = "hidden";
} else {
$this.toggleClass("hidden", false);
localStorage.toggled = "";
}
});
});
.item {
display: flex;
justify-content: space-between;
border: 2px solid;
width: 200px;
padding: 1.3rem;
}
.trigger {
cursor: pointer;
background: blue;
border: 1px solid;
height: 60px;
width: 60px;
}
.box {
background: red;
border: 1px solid;
height: 40px;
width: 40px;
}
.box.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">
<div class="trigger"></div>
<div class="box hidden"></div>
</div>
<div class="item">
<div class="trigger"></div>
<div class="box hidden"></div>
</div>
question from:https://stackoverflow.com/questions/66054648/jquery-localstorage-for-toggling-hidden-class