Keep menu toggle state after page reload

I saw some users need to keep left menu toggle state after page reload, the idea is quite simple, we need something to keep state, localStorage is a good candidate.

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

As usual, here is demo:

Code

As you see in demo, when we hit menu toggle button on top left page, it will toggle sidebar-collapse class of body tag.
We need to store this state into localStorage and re-set it when page is reloaded.

Modules/Common/J.ts

We will need two helper methods to work with localStorage

Views/Shared/_Layout.cshtml

Near bottom of _Layout.cshtml file, we will handle click event of toggle button and store state into storage with key IS_SIDEBAR_COLLAPSE

Views/Shared/LeftNavigation.cshtml

The rest is getting state from storage with key IS_SIDEBAR_COLLAPSE and toogle class sidebar-collapse for body tag

That’s it !

Bonus

If you don’t want side menu push right panel everytime we hover mouse pointer on the menu then we can remove fixed class of body tag, the result will be something like this:

It’s not too bad I guess :)

Share