jQuery Issue - Clash between multiple menus sharing the same class

Hey there! I'm currently diving into the world of jQuery and encountering an issue with my menu. Whenever I click on a menu item with either the "tm-nav-vertical" or "tm-nav-horizontal" class, it removes the .active class from the initial menu item. I want to create a code that can be reused for any menu (such as .menu1, .menu2).

I tried using .siblings but couldn't get it to work.

$(function () {
$('.tm-nav-vertical ul li, .tm-nav-horizontal ul li').click(function () {
    if ($(this).hasClass("tm-dropdown-button")) {
        if ($(this).hasClass("active")) {
            $(this).removeClass('active');
        } else {
            $('.tm-nav-vertical > ul li.active, .tm-nav-horizontal > ul li.active, .tm-dropdown-button').removeClass('active');
            $(this).addClass('active');
        }
    } else {
        $('.tm-nav-vertical ul li.active, .tm-nav-horizontal ul li.active').removeClass('active');
        $(this).addClass('active');
    }
});});

Answer №1

When using calls like:

$('.tm-nav-vertical ul li.active, .tm-nav-horizontal ul li.active')

You may be selecting elements from anywhere within the document.

A better approach is to locate the parent menu first and then target the specific element(s) you wish to modify. To find the parent menu, you can use jQuery's (or even DOM api's) closest() method by passing the class selector of the menu. This will identify the closest ancestor element that matches the provided selector.

var parentMenu = $(this).closest('.tm-nav-vertical, .tm-nav-horizontal');
parentMenu.find('ul li.active').removeClass('active');

If your menu structure is more intricate (multiple levels, multiple ".active" elements, etc.), you may need to implement a more complex solution than a straightforward find().

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

"Create a dynamic entrance and exit effect with Tailwind CSS sliding in and out from

My goal is to create a smooth sliding animation for this div that displays details of a clicked project, transitioning in and out from the right side. This is my attempt using Tailwind CSS: {selectedProject !== null && ( <div classNam ...

Determining the current element's index as I scroll - using Jquery

If I have a series of divs with the class name 'class' that are fixed height and enable auto-scrolling, how can I determine the index of the current 'class' div I am scrolling in? Here is an example: var currentIndex = -1; $(window).sc ...

Refreshing data causes the data to accumulate and duplicate using the .append function in Jquery

I am currently working with a dynamic table that is being populated using AJAX and jQuery. Everything seems to be functioning correctly, however, I am encountering an issue when trying to reload the data as it just continues to stack up. Below is the func ...

Mysterious area located within a flexbox set to display items in a column arrangement

There is a mysterious gap within a flexbox that has a column direction. In the header-left div, I have set up a flexbox with a column direction. It consists of three nested divs: left_text_heading, hero-img, and hero-text. Strangely, there is an unknown s ...

Implementing pagination in a Node.js application using MongoDB.ORCreating

function implementPaginationForDigitalMigrationJoin(req, res, next) { DigitalMigrationForm.aggregate([ // Join with user_info table { $lookup: { from: DigitalMigrationFormList.collection.name, // other ...

Struggling to find the width of an SVG text box or add line breaks after a specific number of characters?

I am currently working on creating an SVG text box using the amazing Raphael library. The content inside this text box comes from a dynamic string that is extracted from an XML document. There are times when this string turns out to be longer than the can ...

Tips for sending a parameter to an onClick handler function in a component generated using array.map()

I've been developing a web application that allows users to store collections. There is a dashboard page where all the user's collections are displayed in a table format, with each row representing a collection and columns showing the collection ...

Deactivate a setInterval function within a Vue.js component

I am facing an issue in my VUE SPA where I have a component running a recursive countdown using setInterval functions. The problem is that the countdown continues running in the background even when I switch to another view, but I want to destroy the setIn ...

Create a parent dropdown class that contains two separate bootstrap dropdowns nested within it

I am encountering an issue with my dropdown menus. I have 2 dropdown menu items under the same parent dropdown class. However, when I click on dropdown action 1, it displays the body of dropdown menu 2 items instead. <!DOCTYPE html> <html> < ...

Arranging an ng-repeat list in a dynamic order

I am currently working with AngularJS and focusing on reordering the ng-repeat list. The list represents online users who can receive messages at any time. When a user receives a message, I update the UI to display the most recent message beneath their nam ...

Vue's Global mixins causing repetitive fires

In an effort to modify page titles, I have developed a mixin using document.title and global mixins. The contents of my mixin file (title.ts) are as follows: import { Vue, Component } from 'vue-property-decorator' function getTitle(vm: any): s ...

Tips for inserting an element in the middle of two elements using HTML

Here is the current structure of my DOM: <body> <h1> </h1> <button> </button> <p> </p> I am trying to dynamically add another p element in between the button and the existing paragraph when the button is cl ...

Prevent users from changing dropdown options after a form submission fails using Javascript and Jquery

Currently, I am pursuing the tech degree at Team Treehouse and my third project involves creating an interactive form. To simplify my issue, I will outline it in bullet points: The credit card payment method should be preselected when the page loads. I n ...

Trouble with minified scripts on a particular server

Apologies if this has already been addressed, but I've been searching for a solution for hours. I created a basic website that works perfectly on my own hosting. However, when I transfer it to new hosting (same company, same package, different server ...

Tips for maintaining the height of the outer div consistent with that of the inner div

I am encountering an issue with an inner div that is used for overlay and set to a min-height property. Despite changes in the overlay's height, the height of the outer div remains unaffected. #outer { width: 70px; height: 70px; background-co ...

Is there a way to make the edges of this table more curved?

I utilized an HTML code generator to easily create this table, but I am struggling to give it rounded borders. .tg { border-collapse: collapse; border-spacing: 0; } .tg td { border-color: black; border-style: solid; border-width: 3px; font- ...

Highchart displays results for each individual line without the use of commas

I am interested in creating a chart using Highchart with three lines. The first two lines will display data similar to [4.12, 3.34, 5.45] / [3.45, 5.45, 3.23], while the third line should be displayed without any commas, showing results like [7, 4, 2]. Can ...

Add elements to the array, extract elements from the array

tag, I am currently facing a challenge with transferring multiple attributes from SharePoint list items into an array (only selected items in a view) and then passing that array to a function where I can extract and use these attributes to create new list ...

Leveraging nested objects within React state

A React child cannot be an object. If you intended to render a collection of children, utilize an array Encountering the error mentioned above has left me puzzled regarding its restrictions. Below is the code where I am facing this issue. It includes an o ...

Keeping the scroll in place on a Bootstrap4 modal while scrolling through content that is already at the top

On my Bootstrap 4 modal, I have encountered an issue with scrollable content. When I am at the top of the content and try to scroll downwards, nothing happens because I am already at the top. However, if I continue to hold the touch without releasing it, t ...