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

How to style a div for printing using CSS

Currently, I am working on a project that has already been completed but now requires some enhancements. To give you an overview, the project includes a search functionality that displays additional details upon clicking on the displayed name in the result ...

Custom sized box causing Bootstrap Navbar to be unresponsive

I am having trouble loading the Bootstrap 3 navbar inside a .box class with specific CSS rules: .box { height: 600px; width: 320px; position: relative; border: 2px solid #eee; } Unfortunately, it is not displaying re ...

Dealing with challenges in integrating ngx-masonry with Angular 14

I am currently working with Angular 14 framework and the ngx-masonry library (https://www.npmjs.com/package/ngx-masonry/v/14.0.1). However, I am facing some issues where it is not functioning correctly. I would appreciate any assistance or guidance on how ...

Use Javascript's JQuery library to apply functionality to a newly inserted and cloned

I am facing an issue while trying to implement JQueryUI's DatePicker on a node. It works perfectly fine for all the existing nodes, but when I use the clone function to add new nodes, it doesn't seem to apply as expected. Here is the function th ...

A more effective strategy for avoiding the use of directives or jQuery in AngularJS

I need guidance on using Angular directives, especially when deciding between JQuery and Angular 1 directives for a particular scenario. Here is an example of my object list: [ { "id":"sdf34fsf345gdfg", "name":"samson", "phone":"9876543210", ...

Animating Angular ng-template on open/close state status

I am looking to add animation when the status of my ng-template changes, but I am unable to find any information about this component... This is the code in my report.component.html <ngb-accordion (click)="arrowRotation(i)" (panelChange)="isOpen($even ...

What language should be used for JSON data formats?

I am dealing with a JSON file named myjson.cfg that has the following structure: { "values": { "a": 1, "b": 2, "c": 3, "d": 4 }, "sales": [ { "a": 0, "b": 0, "c": 0, "d": 0, ...

The unexpected end of input error is caused by an Ajax call that returns a SyntaxError

I recently developed a basic notepad application where users can retrieve a specific file (which essentially translates to a row from MySQL) in order to make edits. When the form is submitted directly to the PHP file without preventing the default behavi ...

Utilizing jQuery to seize events and handle AJAX callbacks

I am attempting to accomplish a simple task: capture any click event and send the URL to a PHP script. When using alert(a); the ajax.php is called every time. However, if I remove it, only once in every 20 clicks will work. I am wondering if this is due t ...

How can a regular number be used to create an instance of BigInteger in jsbn.js?

I attempted both methods: const num1 = new BigNumber(5); And const num2 = new BigNumber(7, 10); However, I encountered the following error: Error: 'undefined' is not an object (evaluating 'num2.nextBytes') bnpFromNumberjsbn2.js:126 ...

Problem with AngularJS Multiselect checkbox dropdown configuration

In my application, I have a pop-up that includes a multi-select dropdown menu. Here is the code for the Multi-Select Dropdown: <select name="edit_tags" class="form-control" id="advisor_article_tagsx" multiple="" required ng-model="article_selected ...

Tips for Implementing CSS Styles on Ruby on Rails HTML Pages

Just starting out with RoR and trying to customize my form with CSS classes. Here's what I have so far: <%= form_tag :action => 'create' do %> <p><label for = "name">Name</label>: <%= text_field ...

Sending numerous arguments to getStaticPaths() in nextjs

I am looking to create two different routes: /midterm/cs611 /finalterm/cs611 My goal is to display distinct content when accessing the /midterm/cs611 endpoint, and different content when accessing the /finalterm/cs611 endpoint. However, I am running into ...

Tips for creating JavaScript event handlers for Laravel forms

Looking to create a form for my Laravel application that includes text input boxes, radio buttons, and optional values. Here is the basic structure of the form: <html> <head> <title>Form Generation</title> <body> <form act ...

What is the best approach to creating a fully rounded capsule using CSS?

I've been having trouble creating a complete capsule in CSS and I'm not achieving the expected outcome. Can anyone assist me in resolving this issue? I am new to CSS. Below is my code: <style> #myStyle { position: relat ...

What is the best way to retrieve all files from a directory on a web server using jQuery?

By using only jQuery (without PHP), I have the following code: var url = "/repository/load/t3.case"; $.get(url, function (data, status, xhr) { console.log(xhr.responseText); }); This code allows me to retrieve a file from the web server. Howe ...

Revamping the design of a menu bar in WordPress

I designed a navigation bar and now I'm looking to customize the CSS for it in WordPress. Specifically, I want to be able to reference the nav bars by name from PHP to CSS. It seems like there are just two dots representing variables. Here is the co ...

Rails Ajax form submission not working

I recently set up a basic Google form on my website and used this website to extract the HTML code for display. However, upon hitting submit, nothing happens - the page seems to be frozen. I'm attempting to redirect the form submission to another page ...

Looking for a way to identify when a DOM element is resized as a result of web fonts loading asynchronously?

Within this div element lies text styled with a custom font via CSS's @font-face attribute. The issue arises when the font hasn't loaded yet, causing a delay in updating the font style of the text within the div. As a result, taking measurements ...

Ways to extract a value from an object with no properties using jQuery

In order to perform statistical calculations like Averages (Mean, Median, Mode) on data extracted from Datatables, I need the automatic calculation to remain accurate even when the table is filtered. While I have managed to obtain the desired values, extra ...