Tips for maintaining the state of my jQuery accordion menu on my website even after refreshing the page

I came across a nested JQuery accordion code that works perfectly, but there's a major issue. When I click on a menu or submenu in my sidebar (a link that redirects to a different URL), the site fails to remember which menu or submenu should be shown or hidden after a refresh (the default state is hiding all except the 1st level ul). Is there any way to make my menu remember its last state before a refresh? Thank you for your assistance.

HTML:

<ul>
    <li>
        <a href="foo1.php">level 2</a>
        <ul>
            <li><a href="foo2.php">a</a></li>
            <li><a href="foo3.php">b</a></li>
        </ul>
    </li>
    <li>
        <a href="foo4.php">level 2</a></li>
        <ul>
            <li>
                <a href="foo5.php">level 3</a>
                <ul>
                    <li><a href="foo6.php">c</a></li>
                    <li><a href="foo7.php">d</a></li>
                </ul>
            </li>

            <li><a href="foo8.php">e</a></li>
            <li><a href="foo9.php">f</a></li>
        </ul>
    </li>
</ul>

Jquery:

$('ul li ul').hide();
$('ul li').click(function(ev) {
  $(this).find('>ul').slideToggle();
  ev.stopPropagation();
});

Real HTML:

<ul class="arrows_list1-1">
   <h3>Naše produkty</h3>
   <div class="menu-produkty-container">
      <ul id="menu-produkty" class="menu">
      [Content has been truncated here for brevity]
      </ul>
   </div>
</ul>

Real Jquery:

$('.arrows_list1-1 li ul').hide();
    $('.arrows_list1-1 li').click(function(ev) {
        $(this).find('>ul').slideToggle();
        ev.stopPropagation();
    });

Answer №1

Our system will analyze the current URL and perform the following actions:

  • Expand the corresponding level of the current URL
  • Show all parent elements with class .sub-menu
  • Show sibling elements with class .sub-menu

Implementation Code:

$('.arrows_list1-1 li ul').hide();
$('.arrows_list1-1 li').click(function(ev) {
    $(this).find('>ul').slideToggle();
    ev.stopPropagation();
});

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

Answer №3

To start, assign a unique class name to each level of your accordion as illustrated below. Additionally, ensure that the onclick event for each level of the accordion is configured to set a cookie indicating the clicked element for tracking purposes.

<ul class="accordion">
  <li>
    <a href="foo1.php" class="lvl1" onClick="setcookie(this)">level 1</a>
    <ul>
      <li class="lvl1" onClick="setcookie(this)"><a href="foo2.php">a</a></li>
      <li class="lvl1" onClick="setcookie(this)"><a href="foo3.php">b</a></li>
    </ul>
  </li>
  <li>
  <a href="foo4.php" class="lvl2" onClick="setcookie(this)">level 2</a>
    <ul>
      <li class="lvl2">
        <a href="foo5.php" class="lvl2" onClick="setcookie(this)">level 3</a>
        <ul>
            <li class="lvl3"><a href="foo6.php">c</a></li>
            <li><a href="foo7.php">d</a></li>
        </ul>
      </li>

      <li><a href="foo8.php">e</a></li>
      <li><a href="foo9.php">f</a></li>
    </ul>
  </li>
</ul>
function setCookie(e) {
  document.cookie="activeAccordion=" + $(e).attr('class');
}

Additionally, upon loading the page, retrieve the stored cookie value and display the active accordion based on the stored value.

$(function(){
  var activeAccordion = getCookie('activeAccordion');
  $('.' + activeAccordion).closest('ul').slideToggle();
});

function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for(var i=0; i<ca.length; i++){
    var c = ca[i].trim();
    if (c.indexOf(name)==0) return c.substring(name.length,c.length);
  }
  return "";
}

Answer №4

Implementing Cookies on Click Event

$('.arrows_list1-1 li ul').hide();
$('.arrows_list1-1 li').click(function(ev) {
    document.cookie="activeAccordion=" + $(ev).attr('id');
    $(this).find('>ul').slideToggle();
    ev.stopPropagation();
});

Upon page load, retrieve the stored cookie to display the correct level.

$(function(){
  var activeAccordion = getCookie('activeAccordion');
  $('#' + activeAccordion).closest('ul').slideToggle();
});

function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for(var i=0; i<ca.length; i++){
    var c = ca[i].trim();
    if (c.indexOf(name)==0) return c.substring(name.length,c.length);
  }
  return "";
}

Answer №5

One effective method is to save the state of the accordion in a cookie whenever it deviates from its default setting, allowing you to retrieve and apply it when the page is refreshed.

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

Utilizing database information to dynamically select Nightwatch.js tests for execution

Currently, I am in the process of configuring nightwatch tests for a specific website. The setup involves assigning testing personas to run tests, which works smoothly in our development environment. However, we face an issue when we need to dynamically ad ...

Having trouble updating the Laravel Session variable?

In my current Laravel project, I've come across a persistent issue. I'm working on implementing a "load more" feature for comments using Laravel and Ajax, where I use a Session variable to keep track of already loaded rows. However, I've bee ...

Transforming Objects into an Array of Objects in Javascript

I am currently in the process of developing an API that allows users to add movies to their wishlist. One endpoint is dedicated to retrieving all the movies currently on the wishlist. To achieve this, I fetch the movie IDs (not from MongoDB) and make addit ...

Sending an array input to PHP

I am having trouble sending an array input to PHP via JavaScript. The posted array does not seem to be showing up in the controller when I try to print it. Here is the relevant code snippet: submitHandler: function(form) { $('input[name="val_prof ...

Our list of divs all have the same classes, but I need to remove one that contains an element with a specific class

I am trying to remove the <div class="chrg-item> element that contains an image with the class .gr, but my current code is not working properly! $('.chrg-item').hasClass('.gr').remove() <div class="chrg-item"> <img src= ...

When the user interacts with the textbox in a gridview, I want to display a checkbox list below the textbox. This can happen either through clicking

Can anyone offer advice on how to display a checkbox list below a textbox in a gridview when the user clicks or hovers over the textbox? Any tips on dealing with similar issues would be greatly appreciated. ...

How to retrieve the href ID in Node.js using app.js

I am facing an issue with sending parameters to the dashboard while using an href link. I want to include an identifier when clicking on the link that will be passed to the dashboard. The most straightforward solution would involve extracting the id or nam ...

Using PHP, let's display the next image

My website showcases image galleries organized in table format, like this: <table id="gallery"> <tr> <td><a href="largeimg.php?imageID=images/seascape/medium.Vietnam 19.jpg&caption= Vietnam, Cat Ba Island, Vietnam - 2015">< ...

One limitation is that you cannot use JQuery to make multiple rows editable simultaneously

I have a unique challenge with implementing an edit button on each row of a dynamic Bootstrap table. I am attempting to toggle the button's icons and, depending on its current state, enable the corresponding row for editing. <td><button typ ...

retrieve the image name of the background using jQuery

How can I use jQuery to extract only the background image name from a div with a background image? I currently get 'http://localhost/xampp/uconnect/images/tour-networks-ss.png' but I only want 'tour-networks-ss.png' Any assistance wi ...

What is the best way to generate an object using the elements of an array as keys?

Consider the following array: const options = [ { uuid: '123312', label: 'hello' }, { uuid: '523312', label: 'there' } ]; We want to transform it into this format: { r ...

When attempting to load a page in Mozilla, the initial DIV code fails to load

When trying to load a page in Mozilla, the first DIV code is not loading. I attempted to load HTML inside using: <div id="mainContent"></div> with the following call: if (destinationURL != null) { $.get(destinationURL, function(data) { ...

What strategies can be employed to prevent the need for custom classes for each individual paragraph or list item in order to maintain consistent styles within a

Bootstrap typically removes default paragraph margins and list styles for a cleaner look. However, there may be cases where you want to maintain the default styles for paragraphs and lists within a section of user-generated content on a Bootstrap 5-styled ...

Styling material-ui textfield: Tips and tricks

I've been grappling with figuring out how to customize a material-ui TextField component. <TextField id="email" label="Email" className={classes.textField} value={this.state.form_email} onChange={this.handle_change('form_e ...

Exploring the features of AngularJS, one can delve into the ControllerAs syntax

Currently, I am in the process of developing a directive and following the guidelines outlined in the John Papa style guide. In line with this, I have adopted the ControllerAs syntax approach and implemented a small directive as shown below: (function() { ...

I am encountering an issue where my Vue navbar is successfully changing the route but not updating the corresponding router-view

I have been working on a single-page application using Vue and I encountered an issue with the navbar when navigating through routes. The problem is that after the first click on a navbar item, the route changes successfully but the router-view does not up ...

Clear all CSS styles applied to a targeted division

My website built on Wordpress links to several CSS files. One specific div has its own unique style that is separate from the main Wordpress styles. Unfortunately, the Wordpress CSS ends up interfering with my custom div's layout. Is there a way in HT ...

A guide on how to cycle through and modify key-value pairs using a Patch Request in MongoDB

I am working on configuring a patch request for the endpoint "/api/user?username=idHere". This patch request should accept a JSON body and update the user in MongoDB with the new key-value pairs. Currently, the line "{$set: {key: req.body[ ...

implementing a feature to save and showcase a list of preferred names using jquery/ajax without the

On my website, individuals have the ability to search for any name from around the globe. Users can add specific names to their favorites list, which they can view on a separate page containing all of the names added during their current session. I would ...

Performing three consecutive Ajax requests in a Rails application

Recently, I developed a custom admin system for a local gym to manage payments, attendance, mailing, sales, and more. While everything is functioning smoothly, there seems to be an issue with the attendance feature. Occasionally, when taking attendance, an ...