Reputation: 35
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 else? I can't 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, but can't find any problem.
Upvotes: 0
Views: 361
Reputation: 1268
That very w3schools - How TO - Collapsibles/Accordion won't work properly, if you don't assign max-height to <div class="panel">
:
CSS:
.panel {
max-height: 0;
}
Upvotes: 1
Reputation: 220
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
Upvotes: 1