Maintain the jquery menu in an open state after it has been

Encountering a common issue, I am having difficulty adapting existing solutions to my unique situation. I am working with a jquery vertical accordion menu intended for navigation across two websites: home.html and research.html. Below is the relevant excerpt from my home.html:

<div id="cssmenu">
<ul>
    <li class='active'><a href='index.html'>Home</a></li>
    <li><a href='research.html'>Research</a>
        <ul>
            <li><a href='research.html#r1'><span>interests</span></a></li>                      
            <li><a href='research.html#r2'><span>preprints</span></a></li>
            <li><a href='research.html#r3'><span>publications</span></a></li>
            <li><a href='research.html#r4'><span>coauthors</span></a></li>
        </ul>
    </li>
</ul>

Here's how the relevant portion of my research.html file appears:

<div id="cssmenu">
<ul>
    <li><a href='index.html'>Home</a></li>
    <li class='active'><a href='research.html'>Research</a>
        <ul>
            <li><a href='research.html#r1'><span>interests</span></a></li>                      
            <li><a href='research.html#r2'><span>preprints</span></a></li>
            <li><a href='research.html#r3'><span>publications</span></a></li>
            <li><a href='research.html#r4'><span>coauthors</span></a></li>
        </ul>
    </li>
</ul>

Additionally, here is the jQuery code snippet in question:

$(document).ready(function(){
$('#cssmenu > ul > li ul').each(function(index, e){
    var count = $(e).find('li').length;
    var content = '<span class="cnt">' + '</span>';
    $(e).closest('li').children('a').append(content);
    });
$('#cssmenu > ul > li > a').click(function() {
    $('#cssmenu li').removeClass('active');
    $(this).closest('li').addClass('active');
    var checkElement = $(this).next();
    if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
        $('#cssmenu ul ul:visible').slideUp('normal');
        checkElement.slideDown('normal');
    }
    if($(this).closest('li').find('ul').children().length == 0) {
        return true;
    } else {
        return false;
    }
    });

Upon clicking 'Research,' the sub-menu expands as expected. However, selecting a sub-menu entry results in the previously opened sub-menu closing. How can this behavior be prevented? Your assistance would be greatly appreciated, taking into account my limited web programming knowledge.

Answer №1

Here is the code snippet for you to try out:

Check out the Demo


$(document).ready(function() {
  $('#cssmenu > ul > li ul').each(function(index, e) {
    var count = $(e).find('li').length;
    var content = '<span class="cnt">' + '</span>';
    $(e).closest('li').children('a').append(content);
  });
  $('#cssmenu > ul > li > a').click(function() {
    $('#cssmenu li').removeClass('active');
    $(this).closest('li').addClass('active');
    var checkElement = $(this).next();
    if ((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
      $('#cssmenu ul ul:visible').slideUp('normal');
      checkElement.slideDown('normal');
    }
    if ($(this).closest('li').find('ul').children().length == 0) {
      return true;
    } else {
      return false;
    }
  });


  var hashTag = window.location.hash;
  if (hashTag != '') {
    $(hashTag).addClass('active');
  }

});
      

#cssmenu,
#cssmenu ul,
#cssmenu li,
#cssmenu a {
  list-style: none;
  text-decoration: none;
}
#cssmenu {
  width: 325px;
  float: right;
  margin-top: 60px;
}
#cssmenu > ul {
  position: fixed;
}
#cssmenu > ul > li > a {
  font-size: 24px;
  font-weight: bold;
  font-family: Gill Sans;
  padding-bottom: 300px;
  color: #005D9A;
}
#cssmenu > ul > li > a > span {
  background: #FFFFFF;
}
#cssmenu > ul > li > a:hover {
  text-decoration: none;
}
#cssmenu > ul > li.active {} #cssmenu > ul > li.active > a {
  color: #C80000;
}
#cssmenu > ul > li.active > a span {
  background: #FFFFFF;
}
#cssmenu span.cnt {
  padding: 0px;
  margin: 0px;
  background: none;
}
/* Sub menu */

#cssmenu ul ul {
  display: none;
  padding-bottom: 15px;
  padding-left: 0px;
}
#cssmenu ul ul li {} #cssmenu ul ul a {
  font-family: Avenir;
  font-size: 18px;
}
#cssmenu ul ul a:hover {
  color: #585858;

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cssmenu">
  <ul>
    <li class='active'><a href='index.html'>Home</a>

    </li>
    <li id="research"><a href='research.html'>Research</a>

      <ul>
        <li><a href='research.html#rarticles'><span>interests</span></a>

        </li>
        <li><a href='research.html#rarticles'><span>preprints</span></a>

        </li>
        <li><a href='research.html#rarticles'><span>publications</span></a>

        </li>
        <li><a href='research.html#rarticles'><span>coauthors</span></a>

        </li>
      </ul>
    </li>
  </ul>
</div>

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

Fixing the issue of a div exceeding the height of its parent div in Tailwindcss

One issue I'm encountering is with my card element, which has a fixed height of h-80 in Tailwind. Typically, I use this card within a grid. However, I recently added a div inside the card that is larger than its parent div, and I want it to scroll ve ...

Basic exam but located in a place that is not valid

Here is a test I am working on: // import {by, element, browser} from "protractor"; describe('intro', () => { beforeEach(() => { browser.get(''); }); it('should have multiple pages', () => { let buttonOn ...

Steps for changing the direction of a dropdown menu to the left instead of the right

I'm having a bit of an issue with my inbox setup. I have a dropdown for it, but the dropdown is appearing off to the right and since it's at the end of my top navbar, it's not very visible. Here is the CSS code for the inbox: .notification ...

The HTML5 Geolocation script functions properly in Chrome, but encounters issues in Safari and other iOS6 browsers

I am facing an issue with my jquery script that works perfectly in Chrome, but encounters problems in the latest version of Safari and all browsers on iOS6. In Safari, the user is prompted for geolocation permission but then the code fails to execute prope ...

"Combining the power of Node.js, mysql, and socket.io

As a beginner with socket.io, I am facing an issue. How can I update and display real-time data from a table in my database without having to restart the node.js server? The table receives new data every 10 seconds. I have followed several tutorials but h ...

Executing a JavaScript script from a C# script: A step-by-step guide

Greetings all! I am currently engrossed in a school project that requires me to populate a paragraph element with data from a table in my database. Initially, I attempted to achieve this task using JavaScript, but due to the connection script being in C#, ...

Is there a way to wrap label text when using Highcharts Grouped Categories?

Is it possible to wrap my label text or increase the cell height to make it responsive? Check out my jsfiddle example. See how the labels are overlapping here Here is the HTML: <div id="container" class="chart-container"></div> And this is ...

SignalR is experiencing an issue with a protocol error that is related to an unknown

I've been trying to implement the concepts from this article on SignalR and Knockout.js, but I'm encountering some issues. Here is the article I am referencing: http://www.codeproject.com/Articles/322154/ASP-NET-MVC-SIngalR-and-Knockout-based-Re ...

Using Regular Expressions to extract EVERY string located between two specified strings

RegEx is both a fascinating and frustrating tool for me. I admire its power, yet there are many nuances that still elude me. I have a JSON feed with extensive data that I need to sift through to capture all instances between two specific strings. Check ou ...

Enhance Vue functionality by adding a versatile mutation that can be utilized across

I am facing a challenge where I have a mutation that needs to be reused in multiple Vuex modules but should only modify the state at each module level. Is there a way to separate out this mutation so it can be easily added to each module's mutations w ...

What is the process for refreshing and creating new markers on a Leaflet map?

Recently, I came across Leaflet and decided to use it instead of Google Maps. I have an API that I want to use for generating and updating map markers to prevent having multiple markers. I've been working on a project which you can view in this fiddle ...

What is the best way to extract the content within a nested <p> element from an external HTML document using the HTML Agility Pack?

I'm currently working on retrieving text from an external website that is nested within a paragraph tag. The enclosing div element has been assigned a class value. Take a look at the HTML snippet: <div class="discription"><p>this is the ...

Ways to create a group label to modify various textboxes when a click event occurs

Is it possible to change multiple textboxes with corresponding labels after a click event? Issue: The current output only displays the value of the last textbox. $(function () { $('a.edit').on('click', function (e) { e.pre ...

Utilize Vue to call a method by providing its name as a string

When designing a navbar, I encountered the need to include a list of buttons. Some of these buttons should act as links, while others should call specific methods. For example, clicking on "Home" should direct the user to /home and clicking on "Log out" sh ...

Utilize jQuery to enclose nested elements within a parent element

There is a Markup presented below, where this HTML content is being generated from Joomla CMS. I am seeking a jQuery method to reorganize this HTML structure without modifying its PHP code. <div class="item column-1"> <div class="page-header"& ...

What is the best method for retrieving values from selected radio buttons?

I am trying to retrieve the values of the selected radio buttons with the name is_external example.html <div class="exter_inter"> External <input type="radio" name="is_external" value="1" <?php if(isset($_GET['status']) &&am ...

How to validate a <select> element with parsley.js when it is dynamically populated with an object?

I'm struggling to validate a <select> element in my form. With the help of knockout.js, I select a location which then populates the Service Point based on the Location chosen. However, when I try to validate the form using parsley.js after pres ...

Attempting to design the appearance of the form fields within a Mat-Card

As someone new to UI development and lacking in-depth knowledge of css, I have been searching for examples to style a login page using Angular Material. My main struggle right now is getting the form fields to expand the width of the card (minus the paddin ...

Issue with Angular 2: Unable to display 404 error page

I have created a custom "404 - page not found" page to handle situations where the user enters a URL that does not match any paths in my web app: export const routerConfig: Routes = [ { component: LandingPageComponent, path: "", }, { ...

Leverage ajax to invoke an ActionResult by passing the value from a text box

When the user updates the QuantityDelivered field and clicks the Accept Button, the number entered in the textbox and ShoeOrderItem are updated via Ajax. @for (int i = 0; i < Model.ShoeOrderItemList.Count(); i++) { <tr> <td class="text-cen ...