Maintain expanded sidebar navigation when page first loads

Below is a Jquery script that I haven't used before, and don't quite understand:

$(document).ready(function () {
    $(".treeview li>ul").css('display', 'none'); // Hide all 2-level ul
    $(".Treeviewcollapsible").click(function (e) {
        e.preventDefault();
        $(this).toggleClass("Treeviewcollapse Treeviewexpand");
        $(this).closest('li').children('ul').slideToggle();
    });
});

This script controls the expansion and collapse of a tree menu in ASP.net mvc 5.

The script is located in ~/Scripts/Treeview.js and called from the ASP.NET mvc _Layout page.

However, when clicking a link on the tree menu to open a new content page, it collapses the tree menu. Is there a way to keep the tree menu open throughout page clicks?

More information can be found here:

Answer №1

There are numerous potential solutions available for this issue.

The main challenge is that Javascript doesn't retain its state, such as variables or DOM settings, between page refreshes. While there are various methods to make Javascript data persist across pageloads, given your current comfort level with jQuery scripting, it may be more efficient to address this primarily from the server side.

Although I'm not well-versed in ASP.net MVC 5, if you can retrieve details regarding the active page where the navigation menu is established, you can leverage this information to designate the appropriate menu item for expansion by adding the "Treeviewexpand" class.

Subsequently, update your jQuery code as follows:

$(document).ready(function () {
    $(".treeview li>ul").each(function(){
        if(!$(this).hasClass('Treeviewexpand')){
            $(this).css('display', 'none'); // Conceal all 2-level ul elements
        }
    });
    $(".Treeviewcollapsible").click(function (e) {
        e.preventDefault();
        $(this).toggleClass("Treeviewcollapse Treeviewexpand");
        $(this).closest('li').children('ul').slideToggle();
    });
});

For a live demonstration, refer to the example provided at: https://jsfiddle.net/1xjr1ndf/

Answer №2

One way to save the state of a tree menu is by utilizing HTML5's local storage feature.

Here is an example implementation:

$(document).ready(function () {
    var treeState = localStorage.getItem('treeState');
    var treeClass = treeState ? treeState : 'Treeviewcollapse';

    $(".Treeviewcollapsible").addClass(treeClass);

    $(".treeview li>ul").css('display', 'none'); // Hide all 2-level ul
    $(".Treeviewcollapsible").click(function (e) {
        e.preventDefault();   
        
        $(this).closest('li').children('ul').slideToggle();

        if ($(this).hasClass('Treeviewcollapse')) {
          $(this).removeClass('Treeviewcollapse').addClass('Treeviewexpand');
          localStorage.setItem('treeState', 'Treeviewexpand');
        } else {
          $(this).removeClass('Treeviewexpand').addClass('Treeviewcollapse');
          localStorage.setItem('treeState', 'Treeviewcollapse');
        }
    });
});

If you have multiple items in the tree that need to be expanded, you can modify the approach to store the selector and its expansion state rather than just the class.

Answer №3

Customized treeview expanding based on selected radio button using jQuery versions 3.4, 3.6, and more. Adjust selectors carefully, considering case sensitivity (e.g., "UL") or including the ".treeview" class when necessary.

$("input[type='radio']").each(
    function(){
        if(this.checked)
            $(this).parents("UL").each(
                function(){
                    this.style["display"] = "block";
                }
            )
    }
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switching images using jQuery when hovering over navigation bar items

I'm attempting to implement a jQuery function that swaps images in the navigation bar based on user hover actions. The image displayed should vary depending on the height of the element being hovered over. Currently, I have the following code which i ...

Can we display just 2 pricing tables instead of 4 and align them in the center?

Apologies for my lack of experience, I am relatively new to this field! I have encountered the following problem: I currently have 4 pricing tables available: 4 pricing tables However, when I attempt to remove 2 pricing tables in order to keep only 2 i ...

Bootstrap 4 row mysteriously shatters apart

I have searched for solutions to this issue but none of them on this forum have been helpful. Hopefully, someone here can offer some assistance. I am facing a problem with displaying 4 columns of data in one row: Here is the code snippet causing the layou ...

Maintain and refresh the chosen option in the dropdown menu

Currently, I am working on designing a form that has a dropdown menu. My goal is to save the option that the user selects upon submission, so that when they return to the page in the future, their selected option remains as the default. I envision somethi ...

What comes next after a CSS transformation?

Imagine trying to rotate a paragraph 90 degrees and position it so that its top-left corner, which becomes the top-right corner after rotation, ends up at the parent block's top-right corner. Here's the HTML: <!DOCTYPE html> <html> ...

The jQuery issue is causing a problem with the Bootstrap dropdown in my Node application

Currently in the process of developing a node app using handlebars. I aim to incorporate a Bootstrap navbar with a dropdown feature within it for the layout. Unfortunately, the dropdown isn't functioning properly due to issues with jquery integration. ...

the border only partially encasing the div

In this snippet of code, the structure is not fully encapsulated within the div element. There are two child divs positioned in a row format. Bootstrap and inline CSS styles have been utilized for the CSS styling. This particular code segment pertains to a ...

Aligning two buttons within a div using Bootstrap

Hello and thank you for taking the time to read this! I am facing an issue with Bootstrap where I cannot seem to center 2 buttons inside a div. Currently, the buttons are aligned to the left. How can I get them centered? Here is the code snippet: <d ...

Do you think there is an excessive amount of code cluttering up my view in CakePHP using the MVC design

I've recently implemented the Google Maps CakePHP Helper by dereuromark to display a map with markers in my view. Each marker on the map has its own listener that triggers an ajax call. While everything is functioning as expected, I'm uncertain ...

CSS Padding Hover Transition solution for Eliminating Flickering Text issue

Is it possible to achieve this? I'm attempting to animate the padding around a centered text link. When the text link is clicked, the padding changes from 20% to 100%, which works correctly. The text is horizontally and vertically centered using CSS ...

Trouble with attaching a click event to a jQuery datepicker

I am attempting to attach a click event to .ui-state-default after a jQuery datepicker has been displayed (I do not have access to the html generating the datepicker so I cannot utilize any datepicker-specific events) and it functions properly using $.bind ...

Steps for splitting a numbered list and adding an image above each item:

I have a challenge I'm trying to tackle with my list: My goal is to create a long, numbered list that is divided into different sections I also want to include an image within each list item and have it display above the numbered title of the sectio ...

Struggling to locate an element with Selenium and Python?

I'm a newcomer to Python/Selenium and I've spent hours searching and thinking about my issue. My task is to extract a specific value from an element on the ticket creation website we use at work. The problem is, the element containing the ticket ...

Does jQuery have a concept of a "true height"?

Could this be considered a silly question? I'm curious to find out if there's a "power" function that can give me the actual height of a div, taking into account the height of elements with "display:none;" as well. Is this just wishful thinking? ...

Encountering an issue when trying to assign a lengthy query to a variable in ASP.NET MVC RAZOR

Could someone please provide me with the format solution for this lengthy script? I am new to ASP and it seems different from PHP. In PHP, you can simply copy and paste a long script, but in ASP, the script needs to be in one long line. Here is a sample s ...

Utilizing form selectors in non-traditional elements

Trying to optimize my website by avoiding nested forms, I have multiple forms loaded via AJAX. Instead of nesting them, I plan to use select and checkbox selectors along with jQuery actions outside the form element. Here's what I have in mind: <di ...

Utilizing inline styles with the asset pipeline feature in Rails

<%= link_to root_path do %> <div class=""> <div style="background-image:<%= image_tag " image1.png "%>"> </div> <div> <h2>Title</h2> <p>Paragraph</p> </div& ...

Broken responsive carousel using bootstrap

Looking for some help with a responsive bootstrap carousel issue. The carousel items adjust themselves below each other when the screen size is reduced. I want them to display as single items in the carousel. Here are the screenshots and the code. Please ...

Does text alignment apply to one tag but not the other?

Hello, I am in the process of creating a basic webpage and encountering some formatting issues. When I apply the style format to one element, it aligns perfectly, but for another element it doesn't seem to be working. I'm certain it's a simp ...

Tips for creating a responsive table using class naming conventions

Currently, I am working with media queries that target specific devices to adjust the display of tables. By using the code provided below, I can modify the table structure based on screen size and device specifications: @media only screen and (max-width: ...