Remove the active class after it has been clicked for the second time

Currently, I am working on a menu/submenu system where I want to toggle active classes when clicked. However, I encountered an issue - if the same menu item is clicked twice, I need to remove the active class. Initially, I tried using jQuery's toggleClass method but it didn't work as expected. Any suggestions or ideas on how to achieve this functionality? Thank you!

$(document).ready(function() {
    $("#menusomething li a").on("click", function() {
        $("#menusomething li a").removeClass("active");
        $(this).toggleClass("active");
    });
});
#menusomething li a{color :green}
#menusomething li a.active{color :red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menusomething" style="padding-left:30px">
                          <li><a href="#">HOME</a></li>
                          <li><a href="#">ABOUT</a></li>
                          <li><a class="target" href="#">CHAPTERS</a>
<ul class="submenu">
                            <li><a href="#">Dallas</a></li>
                                <li><a href="#">Los Angeles</a></li>
                                <li><a href="#">New York</a></li>
                                <li><a href="#">Northern California</a></li>
                                <li><a href="#">Orange County</a></li>
                                <li><a href="#">Phoenix</a></li>
                                <li><a href="#">San Diego</a></li>
                                <li><a href="#">Washington DC</a></li>
                            </ul></li>
                          <li><a href="#">MEMBER SERVICES</a>
                          <ul class="submenu">
                            <li><a href="#">Service</a></li>
                                <li><a href="#">Service2</a></li>
                                <li><a href="#">Service3</a></li>
                                <li><a href="#">Service4</a></li>
                            </ul></li>
                          <li><a href="#">MENU ITEM</a></li>
                          <li><a href="#">MENU ITEM 2</a></li>
                          <li><a href="#">CONTACT</a></li>
                          </ul>

Answer №1

Let's try a different approach:

        $("#menusomething li a").removeClass("active");

If you remove this line along with the toggle, the class will not be added back again, allowing you to actually remove it.

Consider using the following code instead:

$(document).ready(function() {
    $("#menusomething li a").on("click", function() {
        $(this).toggleClass("active");
    });
});

$(document).ready(function() {
    $("#menusomething li a").on("click", function() {
        $(this).toggleClass("active");
    });
});
#menusomething li a{color :green}
#menusomething li a.active{color :red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menusomething" style="padding-left:30px">
  <li><a href="#">HOME</a></li>
  <li><a href="#">ABOUT</a></li>
  <li><a class="target" href="#">CHAPTERS</a>
  <ul class="submenu">
    <li><a href="#">Dallas</a></li>
        <li><a href="#">Los Angeles</a></li>
        <li><a href="#">New York</a></li>
        <li><a href="#">Northern California</a></li>
        <li><a href="#">Orange County</a></li>
        <li><a href="#">Phoenix</a></li>
        <li><a href="#">San Diego</a></li>
        <li><a href="#">Washington DC</a></li>
    </ul></li>
  <li><a href="#">MEMBER SERVICES</a>
  <ul class="submenu">
    <li><a href="#">Service</a></li>
        <li><a href="#">Service2</a></li>
        <li><a href="#">Service3</a></li>
        <li><a href="#">Service4</a></li>
    </ul></li>
  <li><a href="#">MENU ITEM</a></li>
  <li><a href="#">MENU ITEM 2</a></li>
  <li><a href="#">CONTACT</a></li>
  </ul>

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

Issue with error handling in Node and MongoDB when using Express, Mongoose, and the 'mongoose-unique-validator' plugin

I am facing an issue with the 'mongoose-unique-validator' plugin when trying to handle Mongo ValidationError in my custom error handler. Despite other errors being handled correctly, this specific one is not triggering the desired response from m ...

Dynamically align text in the center of an image, vertically

I'm trying to create a hover effect where an image and text are displayed in the center of the image when someone hovers over it. Here is how the HTML looks: <article> <div class="entry-content"> <a href="http://www.linktopost.com"> ...

Refresh the div element's HTML and content using AJAX

I am interested in implementing a feature similar to the StackExchange link found on the top left of the Stack Overflow site. From what I gather, when the stack exchange link is clicked, the following actions take place: The hidden div container becom ...

What is the method for dynamically updating and showcasing a JSON file upon the click of a button?

I'm currently developing an add-on that will display a panel with checkboxes and a save button when a toolbar button is clicked. The goal is to allow users to select checkboxes, then save the selected data in a JSON file that can be accessed and updat ...

Ways to adjust the height of one panel based on the height of surrounding panels

I have a layout with three panels: two on the left side and one on the right. <div class="row"> <div class="col s6"> <div class="panel"> content1 </div> <div class="panel"> ...

Code snippet: Retrieve the previous and upcoming events based on the current date from an array (JavaScript/Angular)

Is there anyone who can assist me with an algorithm? I have a list of events and need to retrieve the next event and previous events based on the current date. For example: I fetch all events from an SQL database like so: events = [ {eventId:1, event ...

Angular JS - A guide to implementing ng-model binding at a later stage

In a large codebase, there is a straightforward scenario that I need help with: There is an Angular APP and Controller already set up and functioning correctly. However, a ng-model element needs to be dynamically created at a later stage (perhaps through ...

What is the best method for passing page props in Next.JS?

One example is using the React Context API to pass props from the _app file to pages. Another scenario involves refactoring a ReactJS routing, where state is passed from app.js to pages through the route definition as shown below: <Route><Compon ...

How can audio be efficiently streamed to the browser in small chunks using JavaScript?

I am currently working on setting up an internet radio station where I want to easily switch songs and overlay sounds. My goal is to limit the audio rate so that the feed can be adjusted before being sent out. Additionally, I would like to provide continuo ...

Preventing jquery from continuing its execution after an event has been successfully handled

I am experiencing an issue with a radio button that triggers a jQuery script upon clicking. The script is supposed to render a form where users can enter a comment. Everything seems to be working fine, the event is detected and the form is rendered, but wh ...

Tips for choosing the injected HTML's List Element (li) while ensuring it remains concealed

How do I hide the list item with iconsrc="/_layouts/15/images/delitem.gif" image when this div is injected by a first party and I am a third party trying to conceal it? $("<style> what should be inserted here ???? { display: none; } </style>") ...

The node server is experiencing difficulties connecting to the mysql database, resulting in a timed out connection error at Connection._handleConnectTimeout

Having trouble establishing a connection with the mysql database. Every time I attempt to start the node server, it keeps throwing a database connection error. The specific error message is as follows: connect ETIMEDOUT at Connection._handleConnectTimeou ...

Access the Windows directory through a custom HTML link

Currently, I am in the process of creating a personalized "website" that contains a collection of links leading to specific items on my computer. When I click on a link, the folder opens within the browser. Is there a way for these links to open Windows Ex ...

Mastering the art of looping through an array efficiently in jQuery using AJAX without unnecessary repetition

I have a jQuery function that extracts values from the wp_localize_script declaration. <script type='text/javascript'> /* <![CDATA[ */ var assjs = {"action":"get_ass_counts","path":"http:\/\/localhost\/wordpress-dev\ ...

Ways to extract the maximum value from a dataset formatted in JSON

My current project involves using highcharts to create data series for plotting the chart, which looks something like this: series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }] I have been considering ...

Styling columns to be inline-flex without taking up the full height

I'm currently working on a project similar to "Trello" or "Zenhub," using a Kanban board with 4 columns placed in a div#board. The columns are set to display: inline flex, creating a neat horizontal alignment. However, I encountered an issue where eac ...

Encountering an issue while trying to launch an Angular application on localhost. Vendor.js resource failed to load

Whenever I compile the code, it runs successfully. However, when I try to serve the application using 'node --max-old-space-size=8192', even though it compiles without any errors, when I open the app in a browser, it returns an error saying "Cann ...

Guide on sending a JSON object to an EJS javascript loop efficiently

Seeking assistance with passing a Json object named myVar to the home.ejs file below. How should I assign the value to the variable called data? <table id="example" class="table table-striped table-bordered dataTable" cellspacing="0" width="100%"> ...

What is the best way to design a form with two dropdown menus, where the options in the second dropdown menu are determined by the selection made in the first dropdown menu

Is it possible to create two select menus using one dictionary in Django, where the values in the second menu are dependent on the key selected in the first menu? In my Django views.py file, I've constructed a dictionary with Projects as keys and cor ...

"Encountering an error with the any type in the useLocation feature while using React Router version 6

https://i.sstatic.net/0YcS9.png What steps should I take to resolve this particular type of error issue? My attempt at passing a custom type did not yield successful results. ...