Active menu after refresh with localStorage

0

I have this code that leaves the menu active and expands.

<li class="menu-item">
  <a href="#" class"active">
    <span>Posts</span>
  </a>
   <ul class="sub-menu">
      <li><a href="#">Ver Posts</a></li>
      <li><a href="#">Novo Post</a></li>
   </ul>
 </li>

$(".menu-item > a").click(function(){
  $(".sub-menu").slideUp();

  if(!$(this).next().is(":visible")) {
    $(this).next().slideDown();
  } 

  $('.active').removeClass('active');
  $(this).addClass('active');

  localStorage.setItem("activeDiv", $(this).index('.menu-item > a'));
 });

 var activeIndex = localStorage.getItem("activeDiv");
 if (activeIndex) {
   $('.menu-item').removeClass('active').eq(activeIndex).addClass('active'); 
 }

How do I do when I click on the "View Posts or New Post" submenu to continue open after page refresh?

    
asked by anonymous 11.05.2017 / 00:03

1 answer

0

When you set the value of the key " activeDiv ", the $ (this) .index ('.menu-item & a') was always passing null .

localStorage.setItem("activeDiv", $(this).index('.menu-item > a'));

To check what amount your key is picking, in Chrome, open Developer Tools and go to the Application tab.

In the following example I used the JSON.parse () and JSON.stringify () methods to work around this problem.

Documentation of Methods

I added a verification of the localStorage within $ (document) .ready () .

If it is true , it does $ ('. sub-menu'). show ();

If you are false , do $ ('. sub-menu').

Example - JSFiddle

    
11.05.2017 / 04:58