How to lock sidebar menu hidden when refresh page

Viewed 1103

I have a sidebar menu that has been successfully hidden and shown. When the sidebar menu is hidden and I refresh the page or browser, the hidden sidebar menu will return to its original appearance, not in the position when it was hidden. The question is how to lock so that the sidebar menu display remains in a hidden position. I've tried several times using javascript but it still fails. Please help thank you.

.sidebar {
height: 100%;
width: 250px;
position: fixed;
left: 0;
top: 0;
z-index: 1000;
background-color: var(--sidebar-color);
color: #fff;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.5), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
transition: all 0.5s ease;
overflow-y: auto;
/* hide scrollbar for IE, Edge and Firefox */
-ms-overflow-style: none;
scrollbar-width: none;

}

.sidebar.expand {
width: 65px;

}

var btnToggle = document.querySelector("#btnToggle");
var sidebar = document.querySelector(".sidebar");

btnToggle.onclick = function() {
    sidebar.classList.toggle("expand");

}

enter image description here

when refresh page

1 Answers

If you want it to be persistent, you need to use localStorage to store the state of the sidebar. Then, when the page reloads, you can read the state from localStorage, and set the class to the sidebar accordingly.

Untested code below:

var btnToggle = document.querySelector("#btnToggle");
var sidebar = document.querySelector(".sidebar");

// When the page loads, use localStorage to set the initial class

if(localStorage.getItem("expand") && localStorage.getItem("expand") == "true"){
  sidebar.classList.add("expand");
}

btnToggle.onclick = function() {
  sidebar.classList.toggle("expand");
  localStorage.setItem("expand", sidebar.classList.contains("expand"));
}

I created a minimal code pen to illustrate how it works. I also included the slide-in-out animation you mentioned in the comments.

Related