Height of the Accordion List

I have a code snippet below for an accordion list that I put together. I initially set the height for all the heading boxes to be uniform, but it seems like box A is displaying larger than the others. Can you help me figure out what went wrong? Any suggestions are appreciated. Thanks!

 (function () {
  var accordions, i;
  
  // Checking browser compatibility
  if (!document.querySelectorAll || !document.body.classList) return;
  
  // Using a function to isolate each accordion
  function makeAccordion(accordion) {
    var targets, currentTarget, i;
    targets = accordion.querySelectorAll('.accordion > * >h1 ');
    for(i = 0; i < targets.length; i++) {
      targets[i].addEventListener('click', function (e) {
        if (e.target.parentNode.classList.contains("expanded")) {
          e.target.parentNode.classList.remove("expanded")
        } else {
          if (currentTarget) 
            currentTarget.classList.remove('expanded');
        
          currentTarget = this.parentNode;
          currentTarget.classList.add('expanded');
        }
      }, false);
    }

    accordion.classList.add('js');
  }

  // Finding all the accordions 
  accordions = document.querySelectorAll('.accordion');

  for(i = 0; i < accordions.length; i++) {
    makeAccordion(accordions[i]);
  }
  
})();
<style>
/* Styling */
body {
  padding: 2%;
}
.p{
padding:5px;
color:#007a5e
}

// More CSS styles...

</style> 
<section class="accordion js"> 
   <section class="sections"> 
      <h1>A</h1>     
<div>
  <input type="checkbox" class="read-more-state" id="post-1" />
  <label for="post-1" class="read-more-trigger"></label>
  <div class="read-more-wrap">
    <div class="read-more-target"><p class="p">Feb</p>
  </div>
</div>
</div>
<br style="line-height: 15px;"/>
// More HTML with sections B and C...
 <br style="line-height: 15px;"/> 
 </section>

Answer №1

Remove the

<br style="line-height: 15px;"/>
elements within the section between the div's and replace them with margin-bottom: 15px on the div's instead.

Additionally, address other issues such as changing padding: 5px on .p to margin.

To resolve overflow from visually hidden elements causing height distortion, add overflow: hidden to

.accordion.js > *:not(.expanded) > *:not(h1)

(function () {
  var accordions, i;
  
  // Ensure compatibility
  if (!document.querySelectorAll || !document.body.classList) return;
  
  function makeAccordion(accordion) {
    var targets, currentTarget, i;
    targets = accordion.querySelectorAll('.accordion > * >h1 ');
    for(i = 0; i < targets.length; i++) {
      targets[i].addEventListener('click', function (e) {
        /*Added code below*/
        if (e.target.parentNode.classList.contains("expanded")) {
          e.target.parentNode.classList.remove("expanded")
        } else {
          if (currentTarget) 
            currentTarget.classList.remove('expanded');
          
          currentTarget = this.parentNode;
          currentTarget.classList.add('expanded');
        }
      }, false);
    }

    accordion.classList.add('js');
  }

  accordions = document.querySelectorAll('.accordion');
  console.log(accordions);
  
  for(i = 0; i < accordions.length; i++) {
    makeAccordion(accordions[i]);
  }
  
})();
/* Body styles */

body {
  padding: 2%;
}

/* All paragraphs */

.p {
  margin: 5px;
  color: #007a5e;
}

/* Accordion Movement*/

.accordion.js > * {
  overflow: hidden;
}

.accordion.js > *:not(.expanded) > *:not(h1) {
  max-height: 0;
  margin-top: 0;
  margin-bottom: 0;
  opacity: 0;
  visibility: hidden;
  overflow: hidden;
}

.accordion.js > .expanded > *:not(h1) {
  opacity: 1;
  visibility: visible;
}

.accordion.js > * > h1 {
  cursor: pointer;
  visibility: visible;
}

.accordion.js > * > *:not(h1) {
  transition: max-height 0.5s, visibility 0.5s, margin 0.5s, opacity 0.5s;
}
... [Further CSS Styles Omitted for Brevity] ...
<section class="accordion js">
  <section class="sections">
    <h1>A</h1>
    <div>
      <input type="checkbox" class="read-more-state" id="post-1" />
      <label for="post-1" class="read-more-trigger"></label>
      <div class="read-more-wrap">

          ... [Content Clipped for Conciseness] ...

    </section>
    
     ... [More HTML Code Sections Omitted for Clarity] ...
     
</section>

Answer №2

The hidden divs within your accordion are set to visiblity: hidden, which conceals the content while still occupying space on the page. Instead of toggling between visibility and opacity, consider changing the display property from block to none. This simple adjustment can simplify your CSS code and improve efficiency.

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

Sharing Data Between Controllers in AngularJS

I am faced with a challenge involving two Angular controllers: function Ctrl1($scope) { $scope.prop1 = "First"; } function Ctrl2($scope) { $scope.prop2 = "Second"; $scope.both = Ctrl1.prop1 + $scope.prop2; //Ideally, I would like to achieve t ...

Issue with Javascript Promise causing failure to populate list with objects

app.get('/zones/:id/experiences', function(req,res) { var zone_key = req.params.id; var recent = []; var ref = firebase.database().ref('participants/'+zone_key+'/experiences'); ref.on("value", function(snapshot) { ...

Changing the color of placeholder text in MUI 5 TextField

Looking to customize the text color and placeholder text color in my MUI TextField component to be green https://i.sstatic.net/NZmsi.png The documentation doesn't provide clear instructions, so I attempted a solution that didn't work: <TextF ...

What is the process for establishing a dependency on two distinct JavaScript files, similar to the depends-on feature found in TestNG?

I am faced with a scenario where I have two separate JS files containing test methods, namely File1 and File2. The requirement is that File2.js should only be executed if File1.js has successfully completed its execution. My current setup involves using ...

React checkbox remains checked even after uncheckingIs this revised version

I am currently working on a React application where I display an array of matches as a list of rows. Each row contains two athletes, and users can use checkboxes to predict the winner for each match. Only one athlete per row can be checked. To keep track o ...

displaying several gltf 3D models simultaneously on a map using mapbox gl and three js

Recently, I encountered an issue with adding glTF 3D models to a map using Mapbox GL and Three.js. It seems that while I can successfully add a single glTF model in a separate layer on the map, I am facing difficulties when trying to add multiple glTF mode ...

Creating an AJAX request using JQuery in a JSP page and sending it to a Spring controller

At the moment, I am in the process of creating two distinct Ajax JQueries to transmit data from a Google Maps JavaScript page (Latitude, Longitude, and Address of the location searched by the user) to my controller class. However, I am encountering differe ...

The addition of the woocommerce_add_to_cart action is causing issues with the website's native add to cart

After creating a node express API that listens for post requests from the woocommerce_add_to_cart webhook, I noticed that the payload it receives is not very useful. body:{ action: 'woocommerce_add_to_cart', arg:'098uoijo098920sa489983jk&ap ...

What causes my image to overlap my navigation bar when I rotate it?

Is there a way to rotate images in CSS without causing them to overlap with other elements on the page? When I try to adjust the rotation property, the image sticks to the top of the page and overlaps the navigation bar. Below is the code snippet: HTML C ...

Achieving nested classes in CSS: a comprehensive guide

I am encountering an issue with my CSS while trying to create a dropdown on hover. The problem seems to be related to nested classes inside a div structure. It appears that the dropdown list is not displaying properly, leading me to believe there might be ...

Fixing Half Screen Sidebars

I have a query regarding my coding problem. I am trying to create two pop-ups that occupy half of each screen. As I am new to JavaScript and jQuery, I want to ensure that I am doing it correctly. Is there a way for the left side to slide out from the left ...

I need to style a blockquote so that it floats to the right, but I also want it to be

I want to enhance the appearance of my blockquotes by giving them a different color background and ensuring they stand out from the regular text. Although using float:right helps achieve this effect, I prefer not to force the blockquote to the right side o ...

Is Dealing with Multiple AJAX Requests a Pain?

Currently, I am utilizing AJAX to retrieve a list of active streams from TwitchTV along with their viewers, updating every second. Sometimes the stream list can become quite long, so my plan is to divide the AJAX requests into 2 or 3 parts: 1) Obtain Numb ...

What steps should I follow to ensure that the processData function waits for the data returned by the getData function in Angular?

After calling the getData function, each object is stored in an array and returned. Now I need the processData function to await these results from getData and then further process them. However, when I try to console.log(cleaningData), I don't see an ...

Is it possible to apply a style change to several components at once using a single toggle switch

I am looking to implement a day/night feature on my web app, triggered by a simple toggle click. While I can easily add this feature to a single component using the navigation menu, I am faced with the challenge of incorporating it into multiple component ...

A warning message has been triggered: 'Script Alert Error - Object

I've been putting in hours on a SUP project that requires some tweaking and I keep running into the issue Script Alert Error: Object expected The code I've added is: $('#bottomOfStart_ScreenForm').before('<div style="display: ...

When generating a docx file with html-docx-js, it lacks the capability to incorporate external CSS class styles into the document

I have been utilizing the html-docx-js module to convert html content into docx format. However, I am facing an issue where most of my CSS is externally loaded and html-docx-js does not apply any styles. Here is a simplified code sample: const html = &ap ...

Exploring the Functionality of Using Multiple Middlewares in Vue.js 3

For my web app project using vue.js 3 and vue-router, I followed a helpful tutorial on implementing middleware pipelines. The tutorial can be found at: https://blog.logrocket.com/vue-middleware-pipelines/. This tutorial demonstrated creating middleware to ...

I am struggling to create a responsive form using Bootstrap

I am facing an issue with my two forms that I want to have a fixed full-screen size. Despite trying different bootstrap options, they are not responsive at lower resolutions. What should I do to make them responsive? Here is the code: <form action=&a ...

Unable to carry out specific tasks in a particular order with GULP

I'm having trouble getting the TASK cssmin to execute after scss. It works fine when the folder destination is not empty and .css files are already compiled with the 'scss' task, but if the folder is empty, the cssmin task doesn't creat ...