Home > Enterprise >  Accordion not working cant find any solution
Accordion not working cant find any solution

Time:10-29

I am trying to add accordion in my HTML page it is not working at all. I am not sure if I was integrating correct version of js (jquery-3.6.0.min.js) Should I import something elseI cant figure it out. This is my code :

index.html

<button class="accordion">Section 1</button>
  <div class="panel">
    <p>Lorem ipsum...</p>
  </div>

index.js

var acc = document.getElementsByClassName("accordion");
var i;

 for (i = 0; i < acc.length; i  ) {
    acc[i].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight) {
  panel.style.maxHeight = null;
} else {
  panel.style.maxHeight = panel.scrollHeight   "px";
}
});
}

Also, I followed this W3S page step by step cant find any problem but still not working. Thanks in advance.

CodePudding user response:

That very w3schools - How TO - Collapsibles/Accordion wont work properly, if you dont assign max-height to <div >:

CSS:

.panel {
  max-height: 0;
}

CodePudding user response:

If you're using jQuery (like you mentioned), you can use the .slideToggle method (https://api.jquery.com/slidetoggle/). Here's an example, which also uses some other handy jQuery methods:

$(".accordion").click(function() {
  $(this).next().slideToggle();
});

Here's a working example on CodePen: https://codepen.io/andyranged/pen/16a51bb5f076bf2348023c000ce7ded0

  • Related