Show parent menu when child menu is clicked

I'm dealing with a menu that has sub-child menus, and the issue I'm encountering is that whenever I choose a child menu after the page loads, the menu collapses. My goal is to have the parent menu open and expanded instead.

This is the HTML Code:


<div id='cssmenu'>
        <ul>
            <li><a href='http://internallink.com/home'><span>Home</span></a></li>
            <li class='active has-sub'><a href='http://internallink.com/products'><span>Products</span></a>
                <ul>
                    <li class='has-sub'><a href='http://internallink.com/product1'><span>Product 1</span></a>
                        <ul>
                            <li><a href='http://internallink.com/subProduct'><span>Sub Product</span></a></li>
                            <li class='last'><a href='http://internallink.com/subProduct'><span>Sub Product</span></a></li>
                        </ul>
                    </li>
                    <li class='has-sub'><a href='http://internallink.com/product2'><span>Product 2</span></a>
                        <ul>
                            <li><a href='http://internallink.com/subProduct'><span>Sub Product</span></a></li>
                            <li class='last'><a href='http://internallink.com/subProduct'><span>Sub Product</span></a></li>
                        </ul>
                    </li>
                </ul>
            </li>
            <li><a href='http://internallink.com/about'><span>About</span></a></li>
            <li class='last'><a href='http://internallink.com/contact'><span>Contact</span></a></li>
        </ul>
    </div>

Here's the JS code:


jQuery(document).ready(function () {
    jQuery('#cssmenu').on("click","li.has-sub .holder",function () {
        var element = jQuery(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('#cssmenu ul li.has-sub').prepend('<span class="holder"></span>');

});

Is there a way to automatically expand the parent menu when selecting a child menu?

Fiddle Link: https://jsfiddle.net/x415mjfq/

Answer №1

Utilize the full, complete URLs within the links to your advantage. By simply applying the document.querySelector with the square bracket selector and the location.href property:

document.querySelector("a[href='" + location.href + "']").classList.add("selected");

After that, you can perform any necessary actions. In this instance, I am adding the selected class.

Fiddle

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

Short-circuiting async flows on non-error events in Node.js

Node implements the CPS convention for callbacks. Typically, when a function encounters an error, it is common practice to either handle the error or callback the error to the parent function by utilizing something like return cb(err). One challenge I fac ...

What is the purpose of creating redirects instead of just "processing" data?

Upon pressing the subscribe button, a form is submitted. Previously, I used axios. The POST request is sent to https://api.skymongoose.com/subscription. Why does it redirect to a blank page even though the URL points to https://api.skymongoose.com/subscri ...

The validation of radio input signals results in an error being returned

For a while now, I've been trying to solve the issue with radio button validation in my current project. Surprisingly, it works fine when there are no other functions in the form besides the radio buttons themselves. I suspect that the problem lies wi ...

Using jQuery to organize object properties based on the value of another property

Within my collection, I have an array of objects structured as shown below. [ {"rel_id": 1,"forward_flag": true,"asset_id":5,}, {"rel_id": 1,"forward_flag": true,"asset_id":8}, {"rel_id": 1,"forward_flag": false,"asset_id":3}, {"rel_id": 2,"forwar ...

Click to slide the div down and up when needed

Currently, I am utilizing the code below to implement a slide up/down effect on a div using JavaScript. The slide down action is triggered by a button, while the slide up action is associated with a close text. My goal is to have the button toggle betwee ...

Empty array returned when using wrapper.classes() with Vue-test-utils and CSS modules

Recently I started using Vue Test Utils along with CSS Modules. My Vue component is all set up with CSS Modules and it functions perfectly in the app as well as in Storybook. Take my BasicButton for example: <template> <button :class="[ ...

Leveraging AJAX for transferring variable from a dynamic HTML table to PHP for executing an update query

Is there a way to insert a value into the input field valor and update the respective row with that value using both the ID and the valor in the update query? I seem to be missing something here, what could it be? Table <?php $IDTipoEquipamento = ...

Trouble linking JavaScript and CSS files in an Express App

Could someone assist me in understanding what is causing my code to malfunction? Why is it that my javascript and css files do not execute when the server sends the index.html file to the browser? I have a simple setup with an html page, javascript file, ...

Using node.js version 10.0.0 to tinker with gulp

I was working on a node.js api project that functioned perfectly with node.js v8.1.4 & npm v5.0.3. However, upon transitioning to node.js v10.0.0 & npm v5.6.0, I encountered the following error: [email protected] ecosystem E:\opensource& ...

Encountering an error when setting up a React-TypeScript ContextAPI

I am currently attempting to understand and replicate the functionality of a specific package found at: https://github.com/AlexSegen/react-shopping-cart Working within a React-Typescript project, I have encountered challenges when creating the ProductCont ...

Is there a way for me to modify this carousel so that it only stops when a user hovers over one of the boxes?

I am currently working to modify some existing code to fit my website concept. One aspect I am struggling with is how to make the 'pause' function activate only when a user hovers over one of the li items, preventing the carousel from looping end ...

What could be causing this array to be blank?

In the process of working on a product feedback app using React for my portfolio, I encountered an unexpected issue. The problem arises in my SuggestionDetails component, where I am fetching the current id with useParams and filtering out the current produ ...

Change the order of the table data elements using the nth-child CSS selector

I need the second td in my table to appear on top of the first one when I resize the screen. @media screen and (min-width: 200px) and (max-width: 872px) { td :nth-child(1) {display:bottom} td :nth-child(2) {display:top} } <table border="0" cell ...

Display content exclusively within a modal specifically designed for mobile devices

I want to implement a feature where a button triggers a modal displaying content, but only on mobile devices. On desktop, the same content should be displayed in a div without the need for a button or modal. For instance: <div class="container&quo ...

I'm having trouble finding the solution to setting a token in my request header

I have been following a tutorial in a book to build the authentication for my app. However, I am facing an issue where after logging in correctly, I am unable to set the token back into the request. The error message that I receive is: Failed to execute ...

Can you please provide a step-by-step guide for using socket.io with TypeScript and webpack, after installing it

Currently, I am experimenting with TypeScript in conjunction with node.js, socket.io, and webpack. To facilitate this setup, I have configured the webpack.config.js, tsconfig.json, and tsd.json files. Additionally, I acquired the typings file for socket.i ...

Retrieve the document from the HTTP response in NodeRed

Working with Node-Red, I'm facing a challenge wherein I need to retrieve a csv file through an API call. Upon making the http request, I received the following response: { "_msgid": "60d0351dcf215557", "payload": "&q ...

When selecting a new tab in HTML, the current page position remains unchanged. However, I would like the page to automatically scroll to the

In the design of my website, I have incorporated buttons that are linked to various pages using navigation tabs. However, when these buttons are clicked, the view maintains its position on the new page (e.g., halfway scrolled through the page). Instead o ...

Appear multiple areas on click with DIV element

I currently have a DIV that reveals another DIV when clicked, and it works perfectly. However, I run into an issue when I try to replicate the effect further down the page with the same ID's - nothing happens. Here is my script: <script> $(docu ...

How to position one div next to another using CSS and HTML

Hey there, I'm facing an issue with creating a sidenav next to a div containing paragraphs and images. I can't seem to make both the sidenav and the other div appear inline. If anyone has any insights on how to solve this problem or spot what I&a ...