Choose all immediate parent items on the list in the mmenu

Currently, I am working on a project and looking to incorporate the jQuery plugin mmenu (). Despite making some customizations to suit my requirements, I am facing a dilemma. In mmenu, clicking on a list entry navigates to the specified href and marks the clicked item as active using the CSS class ".mm-selected". However, I now aim to highlight the parent list item (and its parents up to the root menu) as selected as well. This way, users navigating upwards in the menu can easily identify their current category.

Below is an example of the menu's HTML structure post applying mmenu. The code showcases a menu with 4 main pages (index, page1, page2, and page3) and 3 subpages (2.1, 2.2, 2.3).

<nav id="nav" class="mm-menu mm-horizontal mm-offcanvas mm-hasheader mm-current mm-opened">
    <ul class="mm-list mm-panel mm-opened mm-current" id="mm-0">
        <li class="mm-selected">
            <a href="#/index">Index</a>
        </li>
        <li>
            <a href="#/page1">Page 1</a>
        </li>
        <li>
            <a class="mm-subopen mm-fullsubopen" href="#mm-1"></a>
            <span>Page 2</span>
        </li>
        <li>
            <a href="#/Page 3">Page 3</a>
        </li>
    </ul>
    <ul class="mm-list mm-panel mm-highest" id="mm-1">
        <li class="mm-subtitle">
            <a class="mm-subclose" href="#mm-0">Page 2</a>
        </li>
        <li>
            <a href="#/page2-1">Page 2.1</a>
        </li>
        <li>
            <a href="#/page2-2">Page 2.2</a>
        </li>
        <li>
            <a href="#/page2-3">Page 2-3</a>
        </li>
    </ul>
</nav>

If anyone has insights on how I could achieve this desired functionality, your input would be highly appreciated!

Answer №1

After some experimentation with jQuery, I was able to come up with a solution that works for the scenario discussed earlier. This code snippet utilizes recursion, making it suitable for handling nested menus as well. However, I am open to suggestions on improving this approach.

var nav = $("#nav");

nav.find("li > a:not(.mm-subopen)").click(function () {
    nav.find("li.active").removeClass("active");
    selectParentEntry($(this));
});

var selectParentEntry = function (a) {
    var li      = a.parent(),
        ul      = li.parent(),
        back    = ul.find("li > a.mm-subclose").first(),
        cID     = "#" + ul.attr("id"),
        pID     = back.length ? back.attr("href") : null;

    li.addClass("active");

    if (pID != null) {
        var subOpen = nav.find("ul" + pID + " > li > a.mm-subopen").filter(function () {                 
            var self = $(this);
            if (self.attr("href") === cID) return self;
        }).first();

        if (subOpen) selectParentEntry(subOpen);
    }
};

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

Struggling to retrieve the tagName attribute when clicking in JavaScript

I am trying to extract the tagName of any element within an iframe when it is clicked. Unfortunately, my JavaScript code is not working as expected. As a beginner in JavaScript, I would appreciate some guidance on where I might be going wrong. <div cl ...

Unable to get Discord.js sample code functioning correctly

Despite my best efforts, I can't seem to figure out why this simple example code is not working. As a newcomer to Java Script, I am struggling with understanding why the line GatewayIntentBits.Guilds is causing an error. Surprisingly, when I comment o ...

Analyzing dates using loops in JavaScript

In order to compare dates using JavaScript, I have written a function: function fulljson (){ var db_data; $.ajax({ url: "http://localhost:8888/auction/offers/5", type: "GET", async: true, ...

Decoding user input parameters within a vue module

It seems like I am hitting a wall when it comes to finding solutions for this particular issue. Currently, I have a component that is supposed to retrieve data from a file and display it. My intention is to only pass the filename to the component so that ...

Which is better: JQuery, YUI, or another option for JavaScript and CSS frameworks?

It's been about 6 years since I last dipped my toes into web development. Attempting to re-enter the field, I find myself overwhelmed by all the new technologies and trends. For my upcoming project, I've decided to go with Perl and Catalyst. The ...

Issue with Ajax and Laravel 500 (Server-side Quandary)

I'm having trouble with using AJAX in Chrome. Below is the code snippet from my web.php file: Route::view('menu','home.menu',['categories'=> App\Categories::orderBy('name')->get()->take(11),'a ...

The Express.js main router is functioning properly, however, the other routers connected to it are experiencing

I'm encountering an issue with my routers. The main route /weather is working fine, but other routes connected to it are not functioning properly. app.js const express = require('express'); const weatherRoute = require('./back/routes/w ...

Exception being raised despite handling in JQuery AJAX post request

I am facing an issue with my login JSON service that handles username and password. When I make a call using JQuery 1.10.1 AJAX and input the correct credentials, it functions correctly. However, if I input incorrect credentials, the error function handler ...

Using a conditional statement in a JavaScript loop

Here is the data I have: companyList: [ { company_name: 'company1', item: 'item1' }, { company_name: 'company1', item: 'item2' }, { company_n ...

Struggling to display the retrieved data on the webpage

Code in pages/index.js import React from 'react'; import axios from 'axios'; import ListProducts from '@/components/products/ListProducts'; const getProducts = async () => { const data = await axios.get(`${process.env.AP ...

How can I independently use the draggable and click features in KineticJS?

How can I implement both draggable and click functionalities on the same node in KineticJS? Currently, when I make an element draggable, a click event is also triggered after the drag. You can view the example in JSFiddle at http://jsfiddle.net/matobaa/LZ ...

Using the JQuery post method along with the name attribute

I have a basic form that I would like to submit using jQuery. In my Django code, I have some custom logic that relies on the name attribute of the form (such as if request.POST.get('BoekForm2')). Below is the structure of my page: <script sr ...

Exploring AngularJS to search for and present data in a tabular layout

Can anyone guide me on searching for data within a JSON file and presenting it in a table format? I want the table to be visible only when I click the search button. I would really appreciate it if someone could provide me with instructions or a helpful ...

Applying custom CSS to individual divs based on their text height using jQuery

I have a grid consisting of multiple boxes each sized at 280px by 280px, and I am seeking a way to vertically align text within hover overlays on each box. While my current code successfully aligns the text for the first box, I am encountering issues due ...

Leveraging functions and callback within Node.js

Struggling with node.js and function calls here. The issue is that when I call a function, node.js doesn't wait for it to complete, resulting in empty return values. Below is the code snippet: exports.handle = (event, context,callback) => { switch ...

Is there a way to retrieve the id attribute of an option element from the source component?

When a user makes a selection, I am trying to access the id attribute of the HTMLOptionElement. However, it always returns 0 instead of the actual id I passed (such as 1 or 2) from the select tag: <div class="col-8"> <select (cha ...

Changing the source value of a video according to the selected option in a dropdown selection

Trying to dynamically update the src attribute of a video tag based on the selected option in a select box. Here's my code: <video src="default.mp4" id="videobox">Your browser does not support the video tag.</video> <select id="test"& ...

Map on leaflet with popup next to key

I am facing a scenario where I have a map with a unique legend that is styled either as an SVG or a PNG. The legend is always positioned in the bottom left corner but can be quite large, as users have the option to toggle it on and off. Additionally, the ...

Using Vue Js, I utilized Axios to make a call within a function, receiving and storing the retrieved data into an array

While working inside the function shown in the screenshot, I am encountering an issue when trying to access the data retrieved from the backend using axios.get. After exiting the axios block, the values of the array appear as undefined when I attempt to pr ...

Tips for retrieving data in PHP using an AJAX jQuery request

After following all the advice on how to make a jQuery or Javascript AJAX request to a php file on a server, I encountered an issue with the response. The response I'm getting is: Fatal error: Array callback has to contain indices 0 and 1 in Her ...