Got a nice little accordion going here which uses headings to expand and collapse content below. Everything works the way I want it to, except for one thing: when you expand a section by clicking on the heading, you should be able to click on the heading again to collapse it. What's wrong with this picture?
<script type="text/javascript">
$(document).ready(function(){
$(".haccordion > :header").addClass("h-trigger static").next().addClass("section collapsed").attr("inert","");
document.querySelectorAll('.h-trigger').forEach(el => {
el.setAttribute("tabindex", "0");
el.addEventListener("keydown", e => {
if ([" ", "Enter", "ArrowDown"].includes(e.key)) {
e.target.click();
}
});
});
$(".h-trigger.static").click(function(){
$(this).closest(".haccordion").find(".h-trigger.active").removeClass("active").addClass("static");
$(this).closest(".haccordion").find(".section.expanded").removeClass("expanded").addClass("collapsed").attr("inert","");
$(this).removeClass("static").addClass("active");
$(this).next(".section.collapsed").removeClass("collapsed").addClass("expanded").removeAttr("inert","");
});
$(".h-trigger.active").click(function(){
$(this).removeClass("active").addClass("static");
$(this).next(".section.expanded").removeClass("expanded").addClass("collapsed").attr("inert","");
});
});
</script>
<div class="haccordion">
<h2>Section with a paragraph</h2>
<p>Here is some text content</p>
<h2>Section with a div</h2>
<div>
<h3>Heading</h3>
<p>Here is some content with text and an image</p>
<p><a href="#">Test link</a></p>
</div>
<h2>Section with a list</h2>
<ul>
<li>List item 1</li>
<li>List item 2</li>
</ul>
</div>