What I want to achieve:
I am making a list where I want each item to be collapsible, but I want to hide all of the other list elements when one is collapsed.
When one list item <div>
is "collapsed" and showing, I want to toggle the display of the collapsible to be none and be able to "uncollapse or return to the original collapsible" by a click on the collapsed <div>
.
What I have so far:
var coll = document.getElementsByClassName("collapsecontent");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
}
button.collapsecontent {
display: block;
background-color: orange;
border-color: blue;
border-radius: 20px;
width: 87.5%;
margin-left: 6.2%;
margin-top: 1%;
transition: ease-out 10s;
/*transition broken*/
cursor: pointer;
}
div.content {
display: none;
background-color: orange;
margin-left: 6.2%;
margin-right: 6.2%;
padding: 5%;
border: 2px solid blue;
border-radius: 20px;
cursor: pointer;
}
<ul class="contentbox">
<!--content boxes-->
<button class="collapsecontent" type="button"><li class="contentbox"><h1>Works</h1></li></button>
<div class="content">
<p>Example</p>
</div>
<button class="collapsecontent" type="button"><li class="contentbox"><h1>Other</h1></li></button>
<div class="content">
<p>Example2</p>
</div>
<button class="collapsecontent" type="button"><li class="contentbox"><h1>About</h1></li></button>
<div class="content">
<p>Example3</p>
</div>
<button class="collapsecontent" type="button"><li class="contentbox"><h1>Placeholder</h1></li></button>
<div class="content">
<p>Example4</p>
</div>
</ul>
I am also willing to explore ways other than collapsibles if it achieves the same results, but this was the only way I could think of.
2
Answers
you can hide all content divs except the one currently being clicked and then toggle the display of the clicked item’s content div.
I recommend using details disclosure elements to implement this. Even though your desired behaviour is not an exact match for the default behaviour of such elements, it’s pretty close, and the additional semantics should improve the accessibility of your page.