Code for switching between accordion panels with a simple button press

I took some code snippets from a website and developed a shopping cart accordion module. The complete code is available on my CodePen profile, you can access it through this link:

http://codepen.io/applecool/pen/YXaJLa

<div class="summary">
 <button class="expand btn btn-lg">Collapse All for Summary</button>
</div>

The HTML snippet above includes a button named "Collapse All for Summary" at the bottom. This button's functionality is to toggle all the accordion tabs open or closed when clicked. When initially opening the page, the accordion tabs work smoothly. However, after implementing the toggle button feature using JavaScript, clicking on the tabs no longer functions as expected, likely due to CSS class changes.

Here is the JavaScript function I created for the toggle functionality:

$('.expand').click(function(){

   if($('.accordionItem.is-collapsed').css('max-height')== '0px'){
    $('.accordionItem.is-collapsed').css({
      'max-height': '900px'
     });

   }else if($('.accordionItem.is-collapsed').css('max-height')== '900px'){
    $('.accordionItem.is-collapsed').css({
      'max-height': '0px'
     });

    }

});

Associated CSS rules for the script and button div:

.accordionItem.is-collapsed{
  max-height: 0px;
}

Your assistance in resolving this issue would be greatly appreciated. Any suggestions or workarounds are welcome. Please help me identify and correct any mistakes I may have made. Thank you!

Best regards, .SH

Answer №1

Your code has been enhanced to incorporate expand/collapse functionality, although it may need some cleaning up before implementation. Despite its messy state, it effectively accomplishes the task.

The modifications include using arrays to iterate through single or multiple items depending on whether you click an individual item or the expand/collapse all button. The advantage here is that it retains the core essence of the original code while allowing for toggling classes on several items at once.

Detailed explanations have been added as comments in the JavaScript code.

Answer №2

To dynamically change the CSS class of an element with JavaScript, you can utilize methods like .toggleClass to achieve this. In addition, setting the appropriate value for max-height in your CSS is essential:

** Updated JS **

$('.expand').click(function(){
   $('.accordionItem').toggleClass('is-hidden');
});

** Updated CSS **

.accordionItem {max-height: 800px;}
.accordionItem.is-hidden {max-height: 0px;}

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

Utilizing iPad, Safari, and CSS to effortlessly fill a page with flexbox properties

Trying to create a flex layout that expands the main area to fill the entire height of the display, with a footer always at the bottom when the content is small. However, if the main content exceeds the display size, it should behave like a normal page and ...

Promise-based React Redux Login: An error occurred during login process

I'm currently working on my first React+Redux application and I'm still in the scaffolding phase. As a newcomer to React, I've encountered an issue with my simple login app. The AuthAction returns a Promise from the login(username, password) ...

Exploring byte array manipulation in node.js and techniques for data processing

Currently, I am faced with the challenge of retrieving a full byte array from a socket and then inserting it into a BLOB database without formatting the data. This is necessary as I specifically need to maintain the structure of the byte array. Initially, ...

Hovering over an element and eliminating any extra space

Hey there, I'm looking for some assistance with removing the whitespace on hover. Below is the code along with a screenshot for reference: div.show_sizes_onhover { background: rgba(255,255,255,.9); bottom: -1px; color: #a1a1a1; left: 0; padding: 5px ...

"NgFor can only bind to Array objects - troubleshoot and resolve this error

Recently, I've encountered a perplexing error that has left me stumped. Can anyone offer guidance on how to resolve this issue? ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supp ...

Working with jqgrid: Using a custom formatter to retrieve the column index

How to retrieve column index using custom formatter? In the "Tax" column, I am attempting to use a custom formatter. I need to obtain the column index value and the row index value. While I can fetch the irow parameter with options.rowid, there seems to b ...

Using Ajax to trigger JSON-formatted HTML output

Issue with Populating Modal Window I am encountering difficulties while trying to populate a modal window dynamically with extended information retrieved from a mySQL database. Despite attempting various methods such as nested arrays, while loops, and for ...

When clicking on a checkbox's assigned label, Chrome and IE may experience delays in firing the change event

When a user checks a checkbox under a specific condition, I want to display an alert message and then uncheck the checkbox. To achieve this, I am utilizing the click function on the checkbox to internally uncheck it and trigger necessary events. I have a ...

No location matched any routes

I'm currently working on a notes application, and I've encountered an error when trying to edit the notes. The error message says "No routes matched location id ...". Any idea what could be causing this issue? The approach I'm taking is to ...

Creating Vue Components indirectly through programming

My goal is to dynamically add components to a page in my Vue Single file Component by receiving component information via JSON. While this process works smoothly if the components are known in advance, I faced challenges when trying to create them dynami ...

The click event fails to trigger on dynamically loaded Ajax content

I've encountered an issue while loading content using ajax from external HTML Files. After the content is loaded, the click event doesn't seem to be working in Safari (including mobile safari) for any of the newly loaded elements such as ul, li, ...

Achieving full screen height at 100% with the CSS property of display: table along with table-cell tag

I'm facing an issue with the layout of my page. In this example (http://jsfiddle.net/RR2Xc/2/), the footer is not positioned at the bottom as desired. If I force the footer to be at the bottom, it creates a gap between the sidebar and footer where the ...

Tips on navigating an array to conceal specific items

In my HTML form, there is a functionality where users can click on a plus sign to reveal a list of items, and clicking on a minus sign will hide those items. The code structure is as follows: <div repeat.for="categoryGrouping of categoryDepartm ...

"Integrating JSON data into AMCharts for dynamic data visualization

Having some trouble with my chart rendering properly. The key and column titles are displaying, but the bars for the data values aren't generating. I'm confident in my PHP code and using json_encode to return the data. Below is the data being pa ...

Exploring the Battle of Efficiency: Stateless Components vs. Class Components in the Age of React Hooks - Determining the Superior Approach

Having delved into various online resources and discussions on platforms like Stack Overflow (link here), the consensus seems to lean towards utilizing stateless functions (functional components) whenever possible. Many of the life cycle methods found in ...

Where can the first pixel in the window be located? (using jquery)

Can someone help me with finding the y coordinates of the first visible pixel in the window when I scroll down? I'm having trouble figuring it out. Thanks, Mladen ...

Unlock the mystery of identifying which trace is selected in the plot.ly JS legend

When using plot.ly, it is possible to set up a listener for legend click events. I am wondering how to determine which trace in the legend was clicked on. To provide a more specific example, let's say there are two traces (trace0, trace1) in a line gr ...

What is the best way to integrate ES6 ReactJS code into an Express application?

I am trying to initially render my ReactJS application on the server using ExpressJS. Although I have been able to import ES6 modules using require(), the module crashes upon loading because it contains ES6 code (ES6 import and export). Index Route var ...

What could be causing this JavaScript if statement to consistently evaluate to true?

I'm facing an issue where I want to run a specific block of code when a div is clicked for the first time, and then another block when it's clicked for the second time. The problem is that even though my alert shows the variable being updated wit ...

Mobile device causing issues with appendTo function

I am encountering an issue with my PHP file within an iframe that displays a form result in the parent document using jQuery code. Within the scenario, there is usage of both appendTo for a <p> and an input element. The jQuery code performs well on ...