Issue
I have a toggle button where when the button is clicked, the sidebar will collapse, and when the toggle button is clicked again, the sidebar will return to normal. I want to save the state in local storage, but I'm having problems with how to keep the state in local storage; the method I'm currently using doesn't save that state. What is the correct way to store state in local storage so that when the sidebar collapses, and the page is reloaded, the sidebar will still collapse?
<div id="sidebar"
class="c-sidebar c-sidebar-dark c-sidebar-fixed c-sidebar-sm-show sidebar" >
<button id="header-toggler"
class="c-sidebar-minimizer c-class-toggler header-toggler"
type="button" data-target="_parent" data-class="c-sidebar-minimized">
</button>
<div class="c-sidebar-brand maximized">
<img style="max-width: 100px;"
src="{{asset('images/brand/logo-text-white.png') }}" alt="GhoCalls Logo">
</div>
<div class="c-sidebar-brand minimized">
<img style="max-width: 56px;"
class="p-1" src="{{asset('images/brand/logo-white.png') }}"
alt="GhoCalls Logo">
</div>
<ul class="c-sidebar-nav">
<li class="c-sidebar-nav-item">
<a class="c-sidebar-nav-link" href="#">
<div class="mr-4 icon">
<i class="fas fa-tachometer-alt"></i>
</div>
Dashboard
</a>
</li>
</ul>
</div>
var sidebarArea = document.getElementById("sidebar");
var headerToggle = document.getElementById("header-toggler");
if (localStorage.getItem("collapsed") === "true") {
sidebarArea.classList.add("c-sidebar-minimized");
} else {
sidebarArea.classList.remove("c-sidebar-minimized");
}
headerToggle.addEventListener("click", function () {
if (sidebarArea.classList.contains("c-sidebar-minimized")) {
localStorage.setItem("collapsed", "true");
} else {
localStorage.setItem("collapsed", "false");
}
});
Solution
On click, change class
On the click event, the class never changes, so the if
condition never changes, therefore localStorage never changes.
Add a line to update class before the lines for localStorage.setItem
:
headerToggle.addEventListener("click", function () {
// NEW
// SET STATE - UI
sidebarArea.classList.toggle("c-sidebar-minimized");
// SET STATE - localStorage
if (sidebarArea.classList.contains("c-sidebar-minimized")) {
localStorage.setItem("collapsed", "true");
} else {
localStorage.setItem("collapsed", "false");
}
});
Answered By - Kalnode
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.