1

I want to toggle my menu and save its settings in the cookie. Here is my Jquery code for toggle button:

My HTML

  <div class="nav toggle">
  <a id="menu_toggle"><i class="fa fa-bars"></i></a>
  </div>

My Code

 var $MENU_TOGGLE = $('#menu_toggle')
 $MENU_TOGGLE.on('click', function() {
    console.log('clicked - menu toggle');

    if ($BODY.hasClass('nav-md')) {
        $SIDEBAR_MENU.find('li.active ul').hide();
        $SIDEBAR_MENU.find('li.active').addClass('active-sm').removeClass('active');
    } else {
        $SIDEBAR_MENU.find('li.active-sm ul').show();
        $SIDEBAR_MENU.find('li.active-sm').addClass('active').removeClass('active-sm');
    }

$BODY.toggleClass('nav-md nav-sm');

setContentHeight();
 });

3 Answers3

2

I used localStorage to solve my problem. It's really simple and easy way to store setting locally. I add these two lines.

Here is my code:

 localStorage.setItem('Menu', 'Mini');

 localStorage.setItem('Menu', 'Larg');

Then I added script in my page like this:

<script>
if (localStorage.Menu === 'Mini') {
    $("body").addClass('nav-sm');

} else {
    $("body").addClass('nav-md');
}
</script>
0
document.cookie = "togglesetting=John Doe; expires=Thu, 18 Dec 2017 12:00:00 UTC";

You can put your setting information into any key value pattern in the cookie.

My suggestion is to put a json there and read the togglesetting key from cookies than set your toogle menu appropriately

Volem
  • 597
  • 2
  • 13
0

I just wrote this earlier today for a website that I am building. My preferred method was to add a cookie check to the head. This adds a class to the html that you can attach styling to.

<script type="text/javascript">
  if (document.cookie.replace(/(?:(?:^|.*;\s*)hasClosedMenu\s*\=\s*([^;]*).*$)|^.*$/, "$1") == false) {
    document.documentElement.className += " menu-open "
  }
</script>

Below you will find the function that sets the cookie determining whether the menu is open or not.

$('.menu-toggle').on('click',function(){
  $('html').toggleClass('open-menu');
  if ($('html').hasClass('open-menu')){
    document.cookie = "hasClosedMenu=; max-age=0; domain="+window.location.hostname+"; path=/; ";
  } else {
    document.cookie = "hasClosedMenu=true; max-age=864000; domain="+window.location.hostname+"; path=/; ";
  }
});

I hope this helps.