What is causing jQuery toggleClass to fail in removing a class?

I have successfully implemented a Skills accordion feature, but I am now trying to add a button that toggles all the skill sections at once. However, I am facing issues with jQuery not correctly adding or removing classes on the .accordion-trigger-all element. Initially, I used .click() method, but then switched to .on("click", function) without any success.

$(document).ready(function() {

  $(".accordion .accordion-trigger.accordion-trigger-single:not(.open) + .skill-container").hide()

  $(".accordion .accordion-trigger.accordion-trigger-single").click(function() {

    $(this).next(".skill-container").slideToggle()

    $(this).toggleClass("open")

    toggleAll()

  })

  function toggleAll() {
    if ($(".skill-container").is(":hidden")) {

      $(".accordion .accordion-trigger.accordion-trigger-all h3").html("Open All")
      $(".accordion .accordion-trigger.accordion-trigger-all").removeClass("open")

    } else {

      $(".accordion .accordion-trigger.accordion-trigger-all h3").html("Close All")
      $(".accordion .accordion-trigger.accordion-trigger-all").addClass("open")

    }
  }

  toggleAll()
  //
  $(".accordion .accordion-trigger.accordion-trigger-all:not(.open)").on('click', function() {

    $(".accordion .accordion-trigger.accordion-trigger-single:not(.open) + .skill-container").slideDown()
    $(".accordion .accordion-trigger.accordion-trigger-single:not(.open)").toggleClass("open")

    $(".accordion .accordion-trigger.accordion-trigger-all.open h3").html("Close All")
    $(".accordion .accordion-trigger.accordion-trigger-all").addClass("open")

    toggleAll()

  })

  $(".accordion .accordion-trigger-all.open").on("click", function() {

    $(".accordion .accordion-trigger-single.open + .skill-container").slideUp()
    $(".accordion .accordion-trigger-single.open").toggleClass("open")

    $(".accordion .accordion-trigger.accordion-trigger-all h3").html("Open All")
    $(".accordion .accordion-trigger.accordion-trigger-all").removeClass("open")

  })

})
.accordion .accordion-trigger {
  cursor: pointer;
  text-align: left;
  width: 100%;
  border: none;
  color: #9CA3AF;
  border-bottom: 3px solid #9CA3AF;
  background-color: #F9FAFB;
}

.accordion .accordion-trigger:not(:first-of-type) {
  margin-top: 30px;
}

.accordion .accordion-trigger.open {
  border-bottom: #059669 3px solid;
  background-color: #ECFDF5;
}

.accordion .accordion-trigger h3 {
  padding: 6px;
  font-weight: initial;
  margin: 0;
  color: #9CA3AF;
}

.accordion .accordion-trigger.open h3 {
  color: #059669;
}

.accordion .skill-container * {
  box-sizing: border-box;
}

.accordion .skill {
  display: inline-block;
  text-align: left;
  color: white;
  padding: 10px 0 10px 4px;
  border-radius: 5px;
  background-color: lightgray;
  white-space: nowrap;
  margin: 10px 0;
  overflow: hidden;
  position: relative;
  z-index: 0;
  width: 100%;
}

.accordion .skill::before {
  content: "";
  position: absolute;
  background-color: #312E81;
  border-radius: inherit;
  z-index: -1;
  top: 0;
  bottom: 0;
  left: 0;
  animation: animateLeft 1s ease-out;
  width: var(--l);
}

.accordion .skill:nth-child(even)::before {
  background-color: #374151;
}

@keyframes animateLeft {
  from {
    left: -100%
  }
  to {
    left: 0
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

...
  
</div>

Answer №1

After some investigation, I have come to a solution for this issue: When jQuery is loaded, it assigns an event handler to the

$(".accordion .accordion-trigger-all.open").on('click', function()
, which means it only detects elements that are open initially. However, if the class is removed and the search is conducted again, the element is not found.

The fix is quite simple:

$(".accordion").on('click','.accordion-trigger-all.open', function()

This will attach the event handler to the entire element rather than just those with the class .open

The same approach should be taken for the opposite scenario:

$(".accordion").on('click','.accordion-trigger-all:not(.open)', function()

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

Internet Explorer 10 offers 3D transformation capabilities

My 3D rotating image carousel works well in Chrome and Firefox but not in IE. I am aware that IE10+ does not fully support the preserve-3d tag, and although there are workarounds by applying transforms to the children instead, I have been unsuccessful in ...

The decision will be dependent on the outcomes provided by the $resource promise

I have been working on calling my API with AngularJS to retrieve a list of 'reports' and then displaying them in a modal or saving the sale depending on whether any results were returned. I've been struggling with this for a while and would ...

What is the best way to hide the input field when there are multiple parent classes present?

I am currently implementing dynamic fields with jQuery and everything is functioning correctly. The problem arises when I attempt to remove these fields. After searching on Google and browsing past questions on StackOverflow, I noticed that everyone seems ...

Tips for including a new class in an HTML element

My goal is to add a specific class to an HTML tag, if that tag exists. This is the code I have attempted: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>index</title> <style> ...

Can someone assist me with positioning an HTML child element to appear behind a parent element using CSS?

I need help displaying an HTML element behind a fixed header in my webpage. I want the div element (which is a child of the header) to appear beneath the header like a dropdown menu. However, I've tried adjusting the z-index and position properties wi ...

What is the best way to display the value of a PHP variable in a JavaScript pop-up window?

Here are the scripts I have. A user will input a numerical value like 123 as a parameter in the URL, and the application will retrieve that value from MySQL and display it in the textarea. For example, if you enter "example.com/index.php?id=123" in the UR ...

Images in CSS accordion not displaying correctly in WordPress website

It seems like I am overlooking a simple solution here, but it's escaping me. I'm attempting to make a CSS accordion function where each section links to a page. If you want to view the source refer to this link Here is my test site URL: this l ...

Troubleshooting a CSS problem on a table filled with images - See attached screenshots for

I've been working on a project involving my phpmyadmin database generating a series of 6 images on my website. I've placed them in a table, but now I'm facing some challenges - even though it seemed simple at first! The goal is to display t ...

Maintaining scope integrity in an Angular application with components, including a dialog that utilizes a custom directive

I'm struggling with passing scope to a template rendered from a directive. It seems like it should be simple, but I can't seem to get it to work properly. Here is a simplified version of my HTML: <div ng-app="myApp"> <md-content> ...

magnify within a div with a set width

Looking for a way to make a div both zoomable and scrollable within a fixed-width container using transform: scale(aScaleRatio) for zooming in/out. Check out this demo for achieving the zoom effect. However, the inner div seems to have trouble aligning to ...

Unable to retrieve nested element from its parent

I am facing an issue with accessing a child element's method from the parent element using ref='menu'. When I try to call $refs.menu.show in a button element within the Vue app, it works fine. However, when I try to do the same in a photo el ...

Is there a way to preserve the original color format without converting it to RGB

When applying a hsl color in JavaScript, it ends up being converted to RGB instead of staying as an HSL color. document.body.style.backgroundColor = "hsl(0,100%,50%)" document.body.style.backgroundColor; // "rgb(255, 0, 0)" I wanted to set an HSL color a ...

Error message: Injector Error: R3InjectorError(Standalone[_AppComponent])[_WebService -> _WebService -> _WebService] occurred

Being a student, I must apologize in advance for any mistakes in terminology or gaps in my understanding. I am currently developing an Angular front-end to communicate with my backend API. However, I keep encountering the following error in the web page c ...

Issues with clearRect() function in HTML5 canvas

Recently, I developed a function with the goal of redrawing a square line block that covers the entire page whenever the window size is adjusted. For reference, you can view my code at http://jsfiddle.net/9hVnZ/ However, I encountered an issue: bgCtx.cl ...

Tips for creating a margin on an HTML button's background color

My bootstrap button has dimensions of 46 x 96px and a border radius of 22px. When hovered, I would like the background color to only extend up to 40 x 90px, without filling the entire button. I understand this can be achieved using a box-shadow, but since ...

Delay the rendering of the MUI DataGrid column until after the DataGrid is visible on the screen

Would it be feasible to asynchronously load a column of data in the MUI DataGrid after the table is displayed on the screen? Retrieving this additional data from the database is time-consuming, so I aim to have it appear once the table has fully loaded. T ...

Creating HTML code using Django and JavaScript

Greetings world! I am relatively new to Python and JavaScript, so my coding techniques might seem unconventional to seasoned developers. However, I am eager to learn and improve. I have an HTML page where Django generates some code for a calendar: Here&a ...

Customize the filename and Task Bar name for your Electron app when using electron-packager

My application uses electron packager to build the app on Mac. Here is my package.json configuration: { "name": "desktop_v2" "productName": "desktop v2", "version": "1.0.0", "license": "MIT", "scripts": { "build": "node --max_o ...

Trouble with launching Semantic UI modal

I have implemented a button using Semantic UI and set up a click event to open a modal when clicked, but nothing is happening. When I click on the link, there is no response. I'm unsure what the issue might be. Below is the code for the button: < ...

The responseText property is not defined in JQuery, but it is accessible and functional when using Firebug

Currently, I am in the process of writing a function that retrieves information from the Flickr API and returns it as a JSON object. When inspecting the global variable data, I can see the JSON object displayed in Firebug's console. Additionally, data ...