skip to Main Content

I have a question for you. I’m trying to use localstorage in my dropdown toggle menu. I have the following HTML code:

<li class="nav-item" id="sidebar">
                    <a class="sidebar-heading" href="#thirdSubmenu" data-toggle="collapse" 
                    class="dropdown-toggle">Anagrafica</a>
                    <ul class="collapse list-unstyled" id="thirdSubmenu">
                        <li>
                            <a class="nav-link" href="">
                                <span data-feather="database"></span>
                                Categorie Materiale</a>
                        </li>
                        <li>
                            <a class="nav-link" href="">
                                <span data-feather="database"></span>
                                Sottocategorie Materiale</a>
                        </li>

..

I want that, when I click on Anagrafica and dropdown menu is opened, when I update my page it remains open too, storing if the dropdwon was opened or not. I’have tried the following code but does work. I’m not good at jQuery, so I hope that someone of you could help me.

Here my jQuery code:

    $("#thirdSubmenu li a").on("click", function() {
    var container = $(this).closest("li");
    var selected_item_index = $("#thirdSubmenu li a").index(container);
    localStorage.setItem("sidebar_selected", selected_item_index );
});

$(function() {
    $("#thirdSubmenu li").eq(parseInt(localStorage.getItem("selected_item_index "))).addClass("active");
});

2

Answers


  1. You want to index the parent <li> within it’s siblings

    Try changing

     $("#thirdSubmenu li a").on("click", function() {
        var container = $(this).closest("li");
        var selected_item_index = $("#thirdSubmenu li a").index(container);
        localStorage.setItem("sidebar_selected", selected_item_index );
    });
    

    To

     $("#thirdSubmenu li a").on("click", function() { 
        // get index of parent `<li>` within it's siblings       
        var selected_item_index = $(this).parent().index();
        localStorage.setItem("sidebar_selected", selected_item_index );
    });
    
    Login or Signup to reply.
  2. You can also go with JavaScript Cookies. Store a value in a cookie

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search