DEV Community

Ashwini
Ashwini

Posted on

collapsed menu getting refreshed on page opening

i am developing one sidebar with 3 levels deep using bootstrap
i have divide screen into 2 parts 1 for sidebar and 2nd part to open the form.when i am clicking on sub-sub-menu the collapsed menu list going back to normal please help me

     // JavaScript code to handle menu item clicks and store state in sessionStorage
     $(document).ready(function () {
         // Restore collapsed state from sessionStorage
         $('.collapse').each(function () {
             var isCollapsed = sessionStorage.getItem($(this).attr('id'));
             if (isCollapsed === 'true') {
                 $(this).collapse('hide');
             }
         });

         // Handle menu item clicks
         $('.menu-link').click(function (event) {
             event.preventDefault(); // Prevent the default anchor tag behavior
             var targetCollapse = $(this).next('.collapse');
             targetCollapse.collapse('toggle');
             var isCollapsed = targetCollapse.hasClass('show');
             sessionStorage.setItem(targetCollapse.attr('id'), isCollapsed.toString());
         });

         $('.submenu-link').click(function (event) {
             event.preventDefault(); // Prevent the default anchor tag behavior
             var targetCollapse = $(this).next('.collapse');
             targetCollapse.collapse('toggle');
             var isCollapsed = targetCollapse.hasClass('show');
             sessionStorage.setItem(targetCollapse.attr('id'), isCollapsed.toString());
         });
     });

     // Check if a menu item should be active on page load
     $(document).ready(function () {
         var activeMenuId = sessionStorage.getItem('activeMenuId');
         if (activeMenuId) {
             $('#' + activeMenuId).addClass('active');
         }
     });

     // Update active menu item on click
     $('.list-group-item').click(function () {
         var menuId = $(this).find('a').attr('href').substring(1);
         sessionStorage.setItem('activeMenuId', menuId);
     });
Enter fullscreen mode Exit fullscreen mode

this is my js code

Top comments (0)