I've been working with some code where clicking on a specific button
toggles the visibility of certain contents. It's functionality is satisfactory, but I want to take it a step further. In addition to showing and hiding content, I also want to ensure that only one piece of content can be open at a time. This means that when one content is opened, any other open content should automatically close. However, my attempts to achieve this have failed so far. How can I accomplish this?
This is my current code:
var coll = document.getElementsByClassName("colps");
for (let 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";
coll[i].innerHTML = 'open';
} else {
content.style.display = "block";
coll[i].innerHTML = 'close';
}
});
}
.container {
width: 30%;
}
.colps {
background-color: lightblue;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
outline: none;
font-size: 15px;
}
.active,
.colps:hover {
background-color: dodgerblue;
}
.cont {
padding: 10px;
margin: 0;
display: none;
background-color: #f1f1f1;
}
<div class="container">
<button type="button" class="colps">open</button>
<p class="cont">Lorem ipsum dolor sit amet</p>
<button type="button" class="colps">open</button>
<p class="cont">Lorem ipsum dolor sit amet</p>
<button type="button" class="colps">open</button>
<p class="cont">Lorem ipsum dolor sit amet</p>
</div>