Active menu after refresh with localStorage

Asked

Viewed 281 times

0

I have this code that makes 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 I do for when I click on the "View Posts or New Post" submenu continue opening after page refresh?

inserir a descrição da imagem aqui

1 answer

0


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

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

To check what value your key is picking, in Chrome, open Developer tools and go on the tab Application.

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

Documentation of Methods

I added a localStorage check inside $(Document). ready().

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

If it is false, ago $('.sub-menu'). Hide();

Example - Jsfiddle

  • It worked! But I tried to add other links and when it’s true, everyone stays open.

  • Could you show an example in Jsfiddle? It’s easier to see what’s going on. You can use the same file I passed as an example. Just edit it, press it Update and give me the link

  • I don’t know if it solves your case, but check out the following example. I added a new Key activeDiv2 and did the same in the previous example. https://jsfiddle.net/30mh3syx/5/

  • In the Posts and Categories menu, note that when the true is set when refreshing the page the 2 are open and the active class does not remain. https://jsfiddle.net/30mh3syx/6/

  • This is because the check if (JSON.parse(activeIndex) == 'true') {&#xA; $('.sub-menu').show(); show() in every element with Class sub-menu when activeIndex is true. In the following example I have made the situation by creating new classes, a new key and adding a new check: https://jsfiddle.net/30mh3syx/5/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.