JQuery - ul / li nested list, continues to expand after page reload

I have a ul / li nested list

<ul>
<li>first</li>
<li>second
<ul>
<li>Third</li>
</ul>
</li>
... and so on

I found this jQuery in interweb for use as inspiration, but how do I keep one element open after the page reloads?

<script type="text/javascript">
        $(document).ready(function() {
            $('div#sideNav li li > ul').hide();    //hide all nested ul's
            $('div#sideNav li > ul li a[class=current]').parents('ul').show().prev('a').addClass('accordionExpanded');  //show the ul if it has a current link in it (current page/section should be shown expanded)
            $('div#sideNav li:has(ul)').addClass('accordion');  //so we can style plus/minus icons
            $('div#sideNav li:has(ul) > a').click(function() {
                $(this).toggleClass('accordionExpanded'); //for CSS bgimage, but only on first a (sub li>a don't need the class)
                $(this).next('ul').slideToggle('fast');
                $(this).parent().siblings('li').children('ul:visible').slideUp('fast')
                .parent('li').find('a').removeClass('accordionExpanded');
                return true;
            });
        });
    </script>
+3
source share
5 answers

you can save the current open menu item in a cookie $.cookie('menustate')

it seems: How to remember the last state using jQuery?

+5
source

In the same way, you control the state when transferring data from page to page:

  • Querystring
  • Cookies
  • Message Form / Hidden Field
  • Ajax to and from the server
+2

, , "" . , , js/jq. URL- (http://example/subsite) , ( , / - , ).

    $(document).ready(function(){  
    var pathname = window.location.pathname;  
    var splitpath = pathname.split("/");        
    $("#nav-" + splitpath[1] + "").children().class('current')
}); 

- <li id=nav-subsite> URL /li/whatever. ? , , $.02

+1

JavaScript.

  • accordionExpanded CSS , ( HTML). , , <li> , .
  • AJAX. , "" -.
  • , cookie.

.

0

, , , body :

<body class="home"> <!-- for homepage -->
<body class="about"> <!-- for about page -->
<body class="etc"> <!-- for etc. -->

And try jQuery for this marker and decide on how to process the list tree when the page loads based on which page. You do not need to set any cookies for this, and as long as they have a JS interface (which every user should at this stage), everything is very important.

0
source

Source: https://habr.com/ru/post/1741827/


All Articles