Fariz Anwardeen Fariz Anwardeen - 4 years ago 121
jQuery Question

Sidebar navigation appears and then disappears on page load when using jquery localStorage

I am using the jQuery localStorage to remember the toggled state of the sidebar navigation menu using the following
jQuery code:

$('#wrapper').toggleClass(window.localStorage.toggled);
$('#menu-toggle').on('click',function(e)
{
e.preventDefault();
if (window.localStorage.toggled != "toggled" )
{
$('#wrapper').toggleClass("toggled", true );
window.localStorage.toggled = "toggled";
}
else
{
$('#wrapper').toggleClass("toggled", false );
window.localStorage.toggled = "";
}
});


The code work properly by remembering the toggled state. The problem arises when the page is refreshed. The sidebar navigation menu first appears and then disappears. I already tried setting the display:none in the css but it doesn't seem to work.

The relevant html code:

<a href="#menu-toggle" class="btn btn-default" id="menu-toggle"><span class="glyphicon glyphicon-th-list"></span></a>

<div id="wrapper">
</div>

Answer Source

Below is how I would achieve your goal. Note that I have used a snippet to organize the code but it will not work on SO due to sandboxing not allowing access to local storage. However you can see it in action with this..

Working jsFiddle

/**
 * Feature detect + local reference for simple use of local storage
 * if (storage) {
 *    storage.setItem('key', 'value');
 *    storage.getItem('key');
 * }
 */
var storage;
var fail;
var uid;
try {
  uid = new Date;
  (storage = window.localStorage).setItem(uid, uid);
  fail = storage.getItem(uid) != uid;
  storage.removeItem(uid);
  fail && (storage = false);
} catch (exception) {}
/* end  Feature detect + local reference */

$(function() {

  if (storage) {
    $('#wrapper').toggleClass('isOpen', storage.getItem('isOpen') == '1');
    $('#menu-toggle').on('click', function(e) {
      e.preventDefault();
      var setOpen = storage.getItem('isOpen') == '1' ? 0 : 1; // set opento the oposite of current
      storage.setItem('isOpen', setOpen);
      $('#wrapper').toggleClass('isOpen', setOpen);
    });
  } 
  
});
#wrapper:not(.isOpen) {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#menu-toggle" class="btn btn-default" id="menu-toggle"><span class="glyphicon glyphicon-th-list"></span></a>

<div id="wrapper">
  some content here
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download