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

Is there a JavaScript alternative to wget for downloading files from a specified url?

"wget http://www.example.com/file.doc" can be used to download the file to the local disk. Is there an equivalent way to achieve this in JavaScript? For example, let's look at the following HTML snippet. <html> <head> <script langu ...

The appearance of an SVG image inside an absolutely positioned div varies between Firefox and Chrome

The web page I am working on can be found at the following link: This webpage consists of text and SVG images, with the hex bolts positioned over specific areas of the text. Achieving this effect requires absolute positioning within a relatively positione ...

Adjustable width (100%) and set height for SVG

I am attempting to insert an SVG object onto my HTML page with a width of 100% and a fixed height. Upon viewing my fiddle, you will notice that the height of the dark-grey object changes based on the window proportions, which is not the desired outcome. ...

Integrate buttons for increasing and decreasing with the `<select>` element in HTML

Apologies for what may seem like a trivial question, but I am truly stuck. Despite searching extensively, I cannot find how to create a basic HTML tag with increase and decrease buttons aligned to the right. Your assistance would be greatly appreciated. Th ...

Tips for applying stroke and shadow effects specifically when the mouse is moving over a canvas:

How can we create a shadow and stroke effect for circles drawn using HTML canvas only during mouse hover? I have two circles and would like to add a shadow and stroke effect when the mouse hovers over them. However, the issue is that once the mouse moves ...

Expand the div to fit the rest of the screen following the fixed-size navigation bar

I am looking to create a webpage layout that includes a header, mid section, and footer. In the mid section, I want to have a fixed width navigation bar of 250px, with another div holding the content that stretches to fill the remaining space in the browse ...

jQuery Accordion not showing up on screen

On my FAQ page, I have integrated a jQuery Accordion with a repeater control nested inside to display various questions and answers. The FAQ page utilizes a master page named LaunchPage.Master. Here is the code for LaunchPage.Master: <html> <he ...

Choosing colors for Font Awesome icons

Is there a way to customize the color of a font awesome icon using CSS? I've tried changing the color of everything except font awesome icons with this code: ::selection{ background: #ffb7b7 !important; /* Safari */ } ::-moz-selection { back ...

Interactive mobile navigation featuring clickable elements within dropdown menus

I recently implemented a mobile nav menu based on instructions from a YouTube tutorial that I found here. Everything was working perfectly until I encountered an issue on the 'reviews list' page. The dropdown in the mobile nav is supposed to be ...

Tips for retaining a chosen selection in a dropdown box using AngularJS

How can I store the selected color value from a dropdown box into the $scope.color variable? Index.html: <label class="item item-select" name="selectName"> <span class="input-label">Choose your favorite color:</span> <select id="colo ...

How can I create a CSS animation that fades in text blocks when hovering over an image?

I have been trying to implement CSS3 transitions to create a hover effect where the text and background color fade in when hovering over an image. Despite my attempts with various selectors and transition types, I can't seem to achieve the desired res ...

Toggle button in VueJS that dynamically shows/hides based on the state of other buttons

In my table, I have included options for the days of the week such as Everyday, Weekdays, and Weekend. Each row contains 2 select items to choose start and end times for updates. Additionally, there is a toggle button at the end of each row that enables or ...

Experience a dynamic D3 geometric zoom effect when there is no SVG element directly underneath the cursor

Currently, I am working on incorporating a geometric zoom feature into my project. You can see an example of what I'm trying to achieve in this demo. One issue I've encountered is that when the cursor hovers over a white area outside of the gree ...

Using dangerouslySetInnerHTML in React within a Fragment

In my current project, I have a specific requirement where I need to format text in React and also include HTML rendering. Here's an example of what I'm trying to accomplish: import React, {Fragment} from "react"; import {renderToString} from " ...

A step-by-step guide on uploading a CSV file in Angular 13 and troubleshooting the error with the application name "my

I am currently learning angular. I've generated a csv file for uploading using the code above, but when I try to display it, the screen remains blank with no content shown. The page is empty and nothing is displaying Could it be that it's not ...

Navigating a single page application with the convenience of the back button using AJAX

I have developed a website that is designed to function without keeping any browser history, aside from the main page. This was primarily done for security reasons to ensure that the server and browser state always remain in sync. Is there a method by whi ...

Is it possible to trigger the alert message by utilizing this code snippet?

Is it possible to display a message using this function? var start_database = function() { alert('hello'); }; window.setTimeout(start_database, 1000); ...

Show equally sized elements using a grid system

I need assistance with displaying fields in a row using CSS grid. I want to display 3 fields in a row with equal width, and if there are only 2 fields, they should also have equal widths. Additionally, if there is only one field, it should take up the full ...

What strategies can be implemented to minimize the impact of HTML code on just one specific div (or any other chosen element)?

<div> <b> some example </div> different content This will make the "different content" bold. Is there a way to restrict the impact of <b> only to the <div> element? I have tried looking for JavaScript solutions online but did ...

What is the best way to retrieve data in Vue from Node.js?

app.js router.get('/', (req, res) => { var cart = req.cookies.cart; res.sendFile(path.join(__dirname,'../../src/components/cart.html'),cart); }) shoppingCart.html <body> <div id="shop" class="container mt-3"&g ...