Solution 1 :

This seems to solve it, now I just need to change the Button on click 🙂

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.collapsible {
  background-color: #777;
  color: white;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
}

.active, .collapsible:hover {
  background-color: #555;
}

.content {
  padding: 0 18px;
  display: none;
  overflow: hidden;
  background-color: #f1f1f1;
}

.contentcoll {
  padding: 0 18px;
  display: block;
  overflow: hidden;
  background-color: #f1f1f1;
}
</style>
</head>
<body>

<div class="contentcoll">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
<button type="button" class="collapsible">Open Section 1</button>
<div class="content">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>


<script>
var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var content = this.nextElementSibling;
    var contentcoll = this.previousElementSibling;
    if (content.style.display === "block") {
      content.style.display = "none";
      contentcoll.style.display = "block";
    } else {
      content.style.display = "block";
      contentcoll.style.display = "none";
    }
  });
}
</script>

</body>
</html>

Problem :

I am trying to add two sections to a website both being collapsible, with one being collapsed by default. Combined with a button that if pressed collapses the other section and uncollapses the original one.

I have this collapsible-class as baseline:
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_collapsible

Could someone point me in the right direction of how to modify the script so it acts like I explained?

Thanks!

Comments

Comment posted by Nish

Do you mean click on single button will collapse one and other will expand? And on next click, the previously expanded one will become collapsed and vice-versa?

Comment posted by Kreisball

Yes! but I think I got it, thanks 🙂

By

Leave a Reply

Your email address will not be published. Required fields are marked *