I've been working on creating an animated accordion feature that includes a series of clickable headings. When each heading is clicked, it should toggle to reveal or collapse a content panel underneath. The animation involves transitioning the height and opacity properties of each content panel using CSS. Everything works perfectly when I set a fixed pixel height for the expanded content panels, but my goal is to have flexible heights for them to accommodate varying content lengths.
Here's the code snippet from my current progress. I've defined a CSS class called display_on
for revealing the content panel and utilized calc()
to dynamically calculate the height property in pixels. While the animation behaves as expected for opacity adjustments, I'm facing challenges with the transition effect on the height property. It seems ineffective during expansion and leads to a sudden collapse instead of the smooth movement I desire during the collapse phase. Is there any way to achieve the desired functionality?
You can view a demo of my codepen implementation here: http://codepen.io/artocignus/pen/QGdPWx
Here's the HTML structure:
<h1 class="accordion_heading">
Accordion Heading 1
</h1>
<div class="accordion_panel">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et...
// Repeat for other accordion items
Related CSS styling:
.accordion_heading{
margin: 5px;
font-size: 30px;
color: #blue;
background-color: grey;
padding: 0 1em;
width: 400px;
border-radius: 5px;
}
// Define more CSS rules ...
.display_on{
height: calc(100%);
opacity: 1;
transition: all 1s ease;
}
JavaScript function for toggling the display_on
CSS class:
function accordionToggle(e){
var target = e.target;
if(target.classList.contains('accordion_heading')){
var to_toggle = target.nextElementSibling;
to_toggle.classList.toggle('display_on');
}
}
document.addEventListener('click', accordionToggle);