Looking for a dynamic submenu that remains active even after refreshing the page? Check out the jQuery

I encountered an issue with a menu I created using jQuery. When clicking on a submenu, the site refreshes and then the menu does not remain in the active state. I want it to stay active showing its menu and submenu when clicked. I have also created a fiddle here.

<ul class="menu">
        <li><div><a href="#">PRODUCTS</a></div>
            <ul>
                <li><a href="#">Scada Software</a></li>
                <li><a href="#">Energy Monitoring</a></li>
                <li><a href="#">Tension Monitoring</a></li>
                <li><a href="#">Protocol Gateways</a></li>
                <li><a href="#">Gas Monitoring</a></li>
                <li><a href="#">Led Display</a></li>
            </ul>
        </li>

        <li><div><a href="#">SOLUTIONS</a></div>
            <ul>
                <li><a href="#">Power & energy</a></li>
                <li><a href="#">Process Automation</a></li>
                <li><a href="#">Medical Diagnostics</a></li>
                <li><a href="#">Machine Tools</a></li>
                <li><a href="#">Remote Monitoring</a></li>
                <li><a href="#">Industries</a></li>
            </ul>
        </li>

        <li><div><a href="#">OUR EXPERTISE</a></div></li>
        <li><div><a href="#">ABOUT US</a></div></li>
        <li><div><a href="#">CONTACT US</a></div></li>

    </ul>
    
.menu ul{
        text-align:justify;
        width:300px;
        min-width:500px;
        margin-top:60px;
    }
    .menu ul:after{
        content:'';
        display:inline-block;
        width:100%;
    }
    .menu ul li{
        display:inline-block;
        list-style:none;
        white-space:nowrap;
        margin:0;
        padding:0;
    }
    .menu ul li a{
        text-decoration:none;
        color:#000;
    }
    .menu ul li:hover a{
        color:#CCCC00;
        border-bottom:1px solid #CCCC00;
    }
    .menu ul li ul{
        display:none;
    }

    .menu ul li:hover ul{
        position:absolute;
        display:block;
        text-align:justify;
        width:500px;
        min-width:500px;
        margin:0;
        padding-top:20px;
    }
    .menu ul li:hover ul li a{
        color:#000;
        border:none;
        margin-right:25px;
    }
    .menu ul li:hover ul li:hover a{
        color:#CCCC00;
    }
    .menu li.active a{
        color:#CCCC00;
        border-bottom:1px solid #CCCC00;
    }
    .menu li.active ul{
        position:absolute;
        display:block;
        text-align:justify;
        width:500px;
        min-width:500px;
        margin:0;
        padding-top:20px;
    }
    .menu li.active ul li a{
        color:#000;
        margin-right:25px;
        border-bottom:none;
    }
    .menu li.active ul li:hover a{
        color:#CCCC00;
        margin-right:25px;
    }
    .hide{
        display:none;
    }
    
$(document).ready(function(){

        $(".menu > li > div").click(function(){   
          if(false == $(this).next().is(':visible')) {
            $('.menu ul').slideUp(700);
          }
          $(this).next().slideToggle(700);
        });

        var url = window.location.href;
        var $current = $('.menu li ul a[href="' + url + '"]');
        $current.parents('.menu ul').slideToggle();
        $current.next('.menu ul').slideToggle();

    });
    

Answer №1

It is recommended to utilize distinct URLs in the href attribute that correspond to each individual page. This way, when the page is refreshed, the URL will be altered, allowing for the menu on the page to accurately determine which page is currently active and which menu should be displayed.

Answer №2

UPDATE Your code is perfectly fine as long as you have correctly defined the hrefs, for example:

<li><a href="http://localhost/software">Scada Software</a></li> // In this case, I'm using a localhost illustration for simplicity's sake.

If this setup is not working, double-check the URL.

After var url = window.location.href;, try inserting either of these:

this: console.log('url:' + url);

or this: alert('url:' + url);

This will display the current URL.


To maintain the active state even after page refresh, consider utilizing cookies or another method to store persistent variables. Here's an example showcasing the use of cookies with jQuery: How to set/unset cookie with jQuery?

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

Discovering country code details through the Geonames service API rather than relying on the HTML5 location object

My goal is to retrieve the country code of the user's current location using the Geonames Service API. However, it seems that the API only provides a two-letter country code instead of a three-letter one, which is what I require. To work around this i ...

Is there a way to utilize multiple selectors for a single event?

As a beginner in JQuery, I am currently working on building a Webpage where I have multiple elements visible upon a certain event being called. However, since my code is separated, I am interested in making it more concise by combining the selectors. Belo ...

CSS2DRenderer Reset Feature

My scene, camera, renderer, and CSS2DRenderer are created using this class. I am looking for a way to reset (delete and add again) my CSS2DRenderer in order to remove any previously rendered CSS2DObject. Can you guide me on how to achieve this properly? T ...

Using the jQuery function in conjunction with Infinite Ajax Scroll provides a seamless scrolling

Utilizing jQuery for filtering options can enhance the user experience. For instance, selecting the "dead" option displays only rows with the status "dead". However, when implementing infinite Ajax scroll to load new data from the database, the filter sett ...

The HTML document declaration is missing an error

I encountered an error in my code, here is the snippet: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1. ...

Comparing data in Knockout js

I'm trying to compare the values of the variable name by id, but I'm not sure how to do it. Here is what I have so far: if (this.name == self.copy().indexOf(this.id).name) { alert('equals'); } else { alert('not equals&apo ...

If you scroll quickly, watch out for the flickering of the fadeIn and fadeOut

I have a script that fades in an element once the user scrolls more than 145px from the top of the page. $(window).scroll(function(){ if ($(this).scrollTop() > 145) { $('#fademenu').fadeIn(); } else { $('#fademenu').fadeOut(); } } ...

Preserving filter selections in Datatables and transferring them back to dropdown menus

I have implemented Jquery datatables with dropdown filters in the form of a table. The HTML structure is as follows: <table id="example"> <thead> <tr> <th>Name</th> <th>Position</th> ...

Is create-react-native-app experiencing functionality issues?

As someone who is new to expo and create-react-native-app, I recently encountered a strange issue while learning react-native. Normally, I use create-react-native-app without any problems. However, one day when I tried to create a new project, I was presen ...

What is the best way to eliminate "?" from the URL while transferring data through the link component in next.js?

One method I am utilizing to pass data through link components looks like this: <div> {data.map((myData) => ( <h2> <Link href={{ pathname: `/${myData.title}`, query: { ...

What steps can I take to address the issue of missing modules in an Angular application?

I am facing an issue with my Angular application where I am using two local libraries. Despite having all dependencies declared and imported correctly, the build process continues to throw errors related to missing modules. To give you a better picture of ...

Discovering the content of an internal Database or Table in TYPO3 and showcasing it using JavaScript, JQuery, or AJAX

As a newcomer to TYPO3, I must admit that it's quite intricate, but I'm making progress. All I'm looking for is a simple method to extract content from an internal TYPO3 Database Table that I've set up and send it over to JavaScript/JQ ...

Making sure to detect page refresh or closure using jQuery or JavaScript

Could there be a way to determine if a page has been refreshed or closed using jQuery or javascript? The current scenario involves having certain database values that need to be deleted if the user either refreshes or leaves the page. AJAX calls are bein ...

Cannot POST to /profiles/flash/. GET request is also disallowed for /profiles/flash/

Here I am attempting to incorporate a follow toggle button in a Django template using Django and jQuery AJAX, but encountering an error. Method Not Allowed (POST): /profiles/flash/ Method Not Allowed: /profiles/flash/ I'm unsure where I might be goi ...

The installation of "npm" was completed successfully, however there seems to be an issue when

I am currently facing an issue while trying to set up http-server, bower, and grunt on my Windows machine. After successfully installing them using npm install, I encountered a 'command not found' error when attempting to run the commands. Even a ...

Extend child flex boxes vertically when the main axis is horizontal

My flex boxes have the flex-direction set to row and align-items set to stretch. Despite setting align-self to stretch for the child boxes, they only fill the top part of the browser window. Can someone help me troubleshoot this issue? #containerDiv { ...

The nested jade elements are failing to render

If I have a jade setup with 3 files as follows: 1. //layout.jade doctype html html body block content 2. //index.jade extends layout block content h1 Animals block cat block dog 3. //animals.jade extends index block cat p Meow block ...

"Using JavaScript to initiate a popup window that displays a specific destination link

Whenever I view this code, the iframe popup automatically opens. But I want the iframe to open only when I click the "click me" button. Can someone please assist me with this? I believe it's a simple trick, but as a JavaScript amateur, I am struggling ...

Can Bootstrap be configured to use a single resolution exclusively?

Uncertain about the feasibility, I am initiating this inquiry. Can Bootstrap be utilized solely with one resolution (Medium desktop)? This question arises from the fact that the design I possess is catered towards Medium desktop (970px wide). My intentio ...

Error: Type Error when using custom App and getInitialProps in Next.js

I have a simple app built using the Next JS starter kit, and I am attempting to integrate custom functionality as outlined in the documentation: class MyApp extends App { static async getInitialProps({ Component, router, ctx }) { let pageProps = {}; ...