CSS - Ensure the parent stays open and the submenu remains highlighted upon selection

I have integrated a CSS Vertical menu with submenus into an ASP.Net application on the master page. Clicking on each menu item directs to different aspx pages. However, when clicking on a submenu within an expanded parent menu, the page redirects as expected but collapses the parent menu and does not retain the submenu highlight. I am seeking a solution where the parent menu remains expanded and the selected submenu stays highlighted.

(function($) {
$(document).ready(function() {
    $('#cssmenu li.has-sub>a').on('click', function() {

        $(this).removeAttr('href');
        var element = $(this).parent('li');
        if (element.hasClass('open')) {

            element.removeClass('open');
            element.find('li').removeClass('open');
            element.find('ul').slideUp();
        }
        else {

            element.addClass('open');
            element.children('ul').slideDown();
            element.siblings('li').children('ul').slideUp();
            element.siblings('li').removeClass('open');
            element.siblings('li').find('li').removeClass('open');
            element.siblings('li').find('ul').slideUp();
        }
    });
});
})(jQuery); 

HTML

<div id="cssmenu" >
                    <ul >
                        <li class="highlight">
                            <a  id="upload" href="Upload.aspx" ><span>Upload</span></a>
                        </li>

                       ... (content continues)
                    
                </ul>
            </div>  

CSS

 #cssmenu {
 position: relative;
 margin: 0;
 font-family: 'Roboto Condensed';
 line-height: 1;
 width: 250px;
 } 
 .align-right {
  float: right;
 }
#cssmenu ul {
  margin: 0;
  padding: 0;
  list-style: none;
  display: block;
    }
   ... (CSS styling continues)

Answer №1

The issue arises when the page is reloaded, resulting in the loss of any modifications made to the DOM. One suggestion is to compare the href attributes of all a elements with the current path upon page load. If there is a match, you can then implement your 'opening' functionality. An example of how this could be accomplished is as follows:

$(document).ready(function(){
    $('a').each(function(){
        if($(this).attr('href') == location.pathname.substr(1))
            {
            //implement your 'open' logic here
            }
    });

    // Other code goes here...
});

*Please note that this solution assumes your links have relative paths without query strings and do not include the leading / character (as indicated in your initial question). If your links are absolute, contain query strings, or start with a /, additional string processing may be necessary before comparing $(this).attr('href') with location.pathname.substr(1).

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

"Looking to swap out the Angular theme's CSS stylesheet for your entire application? Here's

I was initially facing an issue while trying to import CSS through index.html as I kept getting a MIME type error: enter image description here The browser refused to apply the stylesheet from 'http://localhost:4200/css/pink-bluegrey.css' because ...

Stop the Bootstrap 5 accordion from expanding when the spacebar is pressed in the header text input

Within my React app using react-bootstrap, I have implemented an accordion component that expands or collapses based on the user's interaction with a text input located in the AccordianHeader component. Interestingly, whenever the spacebar is released ...

Retrieve the value of a related object based on the user's click

Check out this sample code on JSFiddle <a href="#"></a> <a href="#"></a> <a href="#"></a> <a href="#"></a> <div></div> JavaScript: function Product(name, price){ this.name = name; this. ...

Obtaining the height of a jQuery element after it has been appended to another div may result in

I am struggling to make a div scrollable only when it reaches a certain height after adding text to it. The jQuery code I wrote to check the height keeps returning zero. Can anyone offer guidance or suggestions? HelpOverlay.prototype.buildContent = functi ...

Determine in JQuery whether an element is positioned at the top of the screen

My webpage has a div that is initially positioned approximately 100px from the top of the browser window. As the user scrolls down, I aim to create an effect where this div remains in place until it reaches the very top of the screen. At that point, I pl ...

Unable to comprehend the reason why the PHP file is not being invoked by Ajax

Here is the code snippet from my HTML file: <script> $(document).ready(function (event) { $(document).on("click", ".interestbutton", function(e) { var docID = e.target.parentNode.parentNode.id; $.ajax( ...

Difficulty Aligning Header Elements - Combining Navigation and Logo on the Same Line

I am currently facing an issue with positioning a logo and navigation links within a <header> element. When I apply the CSS property text-align:center;, the logo aligns to the center on one line while the navigation links appear on another line direc ...

Navigate to specific element from bootstrap navigation bar

I am in the process of creating a website for a small organization. The website is being constructed using bootstrap 4, and there is a navbar that connects to various flex-containers. I want these connections to smoothly scroll to their respective elements ...

Window backdrop being filled

I am attempting to set a background image that fills the entire window regardless of its size. I have implemented html, css and script as shown below: // Function adaptImage() // Parameters: targetimg function adaptImage(targetimg) { var wheight = $ ...

When attempting to use focusin/focusout, I encountered the following error: Uncaught TypeError - The property 'addEventListener' cannot be read from null

When attempting to utilize the DOM events focusin/focusout, I encountered an error: Uncaught TypeError: Cannot read property 'addEventListener' of null. The issue seems to be originating from main.js at lines 18 and 40. I am using Chrome as my b ...

Looking for recommendations on effective jQuery plugins for drag and drop file uploading?

Can anyone recommend any drag-and-drop jQuery plugins that offer similar functionality to Gmail's attachment dragging and dropping feature? I would like the ability to track the upload progress. However, I am specifically looking for options without ...

Tips on how to horizontally align an icon and text using Material UI

As a newcomer to Material UI, I am facing an issue where my icon and text are not aligned: What I'm aiming for: This is the code I have so far: <div style={{ display: 'inline-flex', VerticalAlign: 'text-bottom', Bo ...

Using a CSS nth-child selector to eliminate the bottom margin of the final row

As I work on creating lists that are displayed in columns of two, each .customer-review-container includes a margin-bottom CSS property like this: <div class="col-md-6"> <div class="customer-review-container"> </div> <!-- en ...

Passing variables to each view in Node.js using Express

Currently working on coding a web-based game and looking to share variables across all views. Each user has their own unique race with various variables, such as commodities (money, energy, etc.) and planets (owned, built, etc). The goal is to display th ...

The importance of white space within email design utilizing table tags in HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html style="opacity: 1;" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv ...

The image must be able to fit within the div container without distorting its proportions

Recently, I created a slider that functions flawlessly. However, I am struggling to make the image fit inside the div without distorting its proportions. I've tried various methods but haven't been able to achieve the desired result. Could you p ...

The combination of two tags can create a powerful and impactful presence

My task is to place two <h3> tags in the same line or paragraph. <h3>This is the first paragraph. </h3> <h3>This is the second paragraph.</h3> I would like the output to look like this: This is the first paragraph. This is Se ...

The behavior of an AJAX call using jQuery is not identical to that of a cURL request

When attempting to make an API call in JavaScript using AJAX provided by jQuery, I encounter an unprocessable entity error (a Pydantic error response from my FastAPI server). What's puzzling is that a curl command works fine. It's unclear to me w ...

In JavaScript, adding elements within a loop does not impact the array's contents outside of the loop

I am struggling with maintaining the content of an array while pushing items onto it inside a loop. Even though the array displays correctly during each iteration, once outside the loop, all information is lost. var result = []; users.find({}, { ...

Just encountered an issue stating "PrismaClient cannot run in the browser" while working with [Next.js]

My initial plan was to log all the IDs of news in my database using console. However, when I executed the code, an error occurred as shown in this image. What is the best way to address and resolve this issue? https://i.stack.imgur.com/ci8G1.png ...