Issue with icons not properly expanding and collapsing in accordion display

Currently, I am in the process of constructing an accordion that consists of multiple children and showcases an open/close icon upon clicking.

The concern I am facing revolves around the behavior of the icons. Everything works smoothly when expanding and collapsing one item at a time. However, problems arise when attempting to open multiple items simultaneously as the icons start behaving strangely, displaying minuses instead of pluses.

I have tried implementing various if-else statements, but unfortunately, I have not had any success thus far.

In case you want to take a look, I have included a link to my CodePen

Answer №1

One way to address this issue is by including the code

$('h4').removeClass("open").addClass("closed");
within the click event function. This will remove the class open from all <h4> elements and add the class closed.

This solution can also be applied using $(.pub-accordion-toggle).

Note: Some adjustments have been made to resolve an error that occurred when clicking on an already open element.

$(document).ready(function() {
  $('.pub-accordion-content').hide();

  $('#pub-accordion').find('.pub-accordion-toggle').click(function() {

    var $this = $(this);
    var toOpen = $this.hasClass("open");
    $('h4').removeClass("open").addClass("closed");


    //Toggle icon
    if (!toOpen) {
      $this.removeClass("closed").addClass("open");
    }

    //Expand or collapse this panel
    $this.next().slideToggle('fast')

    //Hide the other panels
    $(".pub-accordion-content").not($this.next()).slideUp('fast');
  });
});
#pub-accordion {
  padding: 24px;
}

#pub-accordion h4:first-child {
  border-top: 1px solid #ccc;
}

#pub-accordion h4 {
  border-bottom: 1px solid #ccc;
  color: #00539f;
  font-size: 1.6em;
  margin: 0;
  padding: 16px 0 16px 33px;
  cursor: pointer;
}

#pub-accordion .closed {
  background: url(http://www.dcholloway.co.uk/codepen/primary-collapse-icon.png) no-repeat 0 13px;
}

#pub-accordion .open {
  background: url(http://www.dcholloway.co.uk/codepen/primary-expand-icon.png) no-repeat 0 13px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Size Guide - - - - - - - - - - - - - - - - -->
<div class="row row__im impage--no-margin">
  <div class="page">
    <div class="row">
      <div class="s-100 m1-100 m2-100 l-100">

        <div id="pub-accordion">
          <h4 class="pub-accordion-toggle closed">Boys size guide</h4>
          <div class="pub-accordion-content default">
            <p>Lorem ipsum dolor sit amet mauris eu turpis.</p>
          </div>
          <h4 class="pub-accordion-toggle closed">Girls size guide</h4>
          <div class="pub-accordion-content">
            <p>Lorem ipsum dolor sit amet mauris eu turpis.</p>
          </div>
          <h4 class="pub-accordion-toggle closed">Boys plus fit size guide</h4>
          <div class="pub-accordion-content">
            <p>Vivamus facilisisnibh scelerisque laoreet.</p>
          </div>
          <h4 class="pub-accordion-toggle closed">Girls plus fit size guide</h4>
          <div class="pub-accordion-content">
            <p>Vivamus facilisisnibh scelerisque laoreet.</p>
          </div>
        </div>


      </div>
    </div>
  </div>
</div>

Answer №2

To enhance the functionality, simply insert the following line at the start of the click event.

$(".menu-item").removeClass('active');

The modified code will appear as follows:

$('#menu-accordion').find('.menu-item').click(function(){
    $(".menu-item").removeClass('active');//this line here
    var $clickedItem = $(this);

    // Toggle active class
    $clickedItem.toggleClass("active");

    // Expand or collapse the panel
    $clickedItem.next().slideToggle('fast');

    // Hide other panels
    $(".menu-content").not($clickedItem.next()).slideUp('fast');
});

This line essentially removes any existing active classes from the .menu-item element. That's its purpose.

View Updated Pen

Answer №3

After closing the panel, make sure to replace the icon with the updated function in the jQuery code.

$('.pub-accordion-content').hide();

$('#pub-accordion').find('.pub-accordion-toggle').click(function() {

  var $this = $(this);

  // Update the icon here
  $(".pub-accordion-toggle").removeClass("open");

  // Hide other panels
  $(".pub-accordion-content").not($this.next()).slideUp('fast');

  // Toggle the icon
  $this.toggleClass("open");

  // Expand or collapse this panel
  $this.next().slideToggle('fast')

});
#pub-accordion {
  padding: 24px;
}

#pub-accordion h4:first-child {
  border-top: 1px solid #ccc;
}

#pub-accordion h4 {
  border-bottom: 1px solid #ccc;
  color: #00539f;
  font-size: 1.6em;
  margin: 0;
  padding: 16px 0 16px 33px;
  cursor: pointer;
}

#pub-accordion .closed {
  background: url(http://www.dcholloway.co.uk/codepen/primary-collapse-icon.png) no-repeat 0 13px;
}

#pub-accordion .open {
  background: url(http://www.dcholloway.co.uk/codepen/primary-expand-icon.png) no-repeat 0 13px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row row__im impage--no-margin">
  <div class="page">
    <div class="row">
      <div class="s-100 m1-100 m2-100 l-100">

        <div id="pub-accordion">
          <h4 class="pub-accordion-toggle closed">Boys size guide</h4>
          <div class="pub-accordion-content default">
            <p>Lorem ipsum dolor sit amet mauris eu turpis.</p>
          </div>
          <h4 class="pub-accordion-toggle closed">Girls size guide</h4>
          <div class="pub-accordion-content">
            <p>Lorem ipsum dolor sit amet mauris eu turpis.</p>
          </div>
          <h4 class="pub-accordion-toggle closed">Boys plus fit size guide</h4>
          <div class="pub-accordion-content">
            <p>Vivamus facilisisnibh scelerisque laoreet.</p>
          </div>
          <h4 class="pub-accordion-toggle closed">Girls plus fit size guide</h4>
          <div class="pub-accordion-content">
            <p>Vivamus facilisisnibh scelerisque laoreet.</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

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

Is there a way to substitute a custom <form> element for the default <form> in an already existing plugin?

I am currently in the process of customizing a theme and a plugin within WordPress. In the plugin, there is a button that allows users to click on it to bring up a form where they can ask questions. While I want users to post their questions through this p ...

Update data in the datatables using values from an array list

Currently, I have two HTML files where I am loading data using JSON and then applying jQuery datatables to them. Now, I need to refresh the data with new parameters. For example: JSON: [ {"name":"jon","sales":"100","set":"SET1"}, {"name":"charlie","sale ...

What are some strategies to enhance the responsiveness of this JQuery code?

I'm facing an issue while trying to create a progress bar that dynamically adjusts based on the device's width. In this particular scenario, whenever the device width changes, the progress bar's width remains static, causing it to break whe ...

Is it possible to have evenly spaced divisions within a fixed wrapper?

I have been experimenting with creating a dynamic navbar that remains at the top of a webpage. Here's what I have so far: <style> .sticky-nav-wrapper > div { color: #000000; display: inline-block; display: -moz-inline-box; * ...

Autofill functions may not be compatible with input fields generated using JavaScript

Having trouble with browsers not using autocomplete in login overlays generated with JavaScript? It can be really annoying. Any suggestions on how to fix this issue? Should I create a hidden form within the original HTML and then move it into the overlay? ...

Using JQuery, identify cells located in the first column of a table excluding those in the header section

In the past, I had code that looked like this: $(elem).parents('li').find(...) I used this code when elem was an item in a list, making it easy to reference all items in the list. But now, I've made some changes and decided to use a table ...

Implementing jQuery function to hide or show content upon page load

Is there a way to have the content hidden when the page is first opened, but then revealed once a button is clicked? Any suggestions? <script> $(document).ready(function(){ $("#rooms").click(function(){ $("#rooms_box").show(); }); $("#faciliti ...

Unable to display results in the control: select2 version 4 ajax data is not showing up

Ever since transitioning to version 4 of the select2 plugin, I've encountered an issue with my ajax requests. Although I receive a response in the console showing as an array, the results are not appearing in the select2 control. The HTTP response l ...

The event handler attached to the 'click' event will only be triggered upon the second click

After implementing the script, I noticed a strange behavior. When I click it on load, everything works perfectly. However, when I click it via a dynamically created element, the HTML seems to shift or stretch on the first click before returning to normal. ...

What is the best way to reveal the following div while concealing the one before it?

Just starting out with Javascript, I'm currently developing a quiz solution that utilizes divs and buttons to navigate through the questions. I've written some JavaScript code for this functionality but I'm encountering an issue where it doe ...

Arranging Nav Items in a Stack with Bootstrap 4

Struggling to create a unique navigation bar design with fixed elements on both the left and right sides. The challenge arises when scaling down to mobile, as the icons on the right end up stacking. Any suggestions on how to resolve this issue? <div ...

CSS tip: Display only the latest x entries on a list

Can CSS be used to display only the most recent x items in a list? The code below reveals every item except the first two. How can I make it so that only the last two items are displayed in the list? ul li { display: none !important; } ul li:nth-las ...

Step-by-step guide on creating a half-circle outline without filling in the shape

Can someone show me how to create a design like this using CSS? ...

Tips on using PHP to populate a Bootstrap popover

Although this question may have been asked previously, I have gone through the answer, tried to implement it, but I am encountering a small issue. While working on a PHP file, I attempted to create an anchor tag and display it in a popover. However, inste ...

CSS and JavaScript issues causing compatibility errors with Internet Explorer

Recently, I've been working on a portfolio website just for fun, and I'm encountering compatibility issues specifically in Internet Explorer. Surprising, right? The issue seems to be stemming from the flipcard.css and flipcard.js files. While oth ...

Responsive design issues with Bootstrap Popover

Whenever I open the popover for the first time, the image is not displayed correctly. How can I ensure that it always shows correctly? Here is a link to the issue: https://jsfiddle.net/n2Lfro30/1/ Below is the button code causing the problem: <button ...

Determine the Number of Table Columns Using jQuery

I'm curious, with jQuery how can one determine the number of columns in a table? <script> alert($('table').columnCount()); </script> <table> <tr> <td>spans one column</td> <td ...

"Troubleshooting a problem with the value of a radio button

I am struggling with a form that contains three sets of radio buttons, each with values ranging from 0 to 3. I have JS/JQ code that is supposed to calculate the total points based on the selected radio buttons and display a specific response accordingly. H ...

How can I send a value from a for loop to a URL within a modal using Django?

Currently, I am working on a project that involves using a for loop with buttons and their corresponding pk values. {% for obj in all_objects %} <button data-toggle="modal" data-id="{{ obj.pk }}" data-target="#myModal" class="open-my-modal"> {{ ob ...

I am currently experiencing an issue where the list items bullets (<ul>) and numbers (<o>) are not displaying correctly on my webpage, even after using the overflow-x: hidden

I am facing a challenge with my web page where the list items are not displaying the usual dots and numbers next to them. Interestingly, when I remove the overflow-x: hidden; property in my CSS, the list item numbers and dots show up immediately, although ...