I successfully implemented this solution using a ResizeObserver. By assigning an id to the collapsible container for easier querying, I then attached an observer to it. Whenever there is a dimension change, the container will automatically be scrolled into view:
// https://www.w3schools.com/howto/howto_js_collapsible.asp
var coll = document.getElementsByClassName("collapsible");
var i;
let collapsibleContainer = document.getElementById("container");
let resizeObserver = new ResizeObserver(entries => {
// Ensure that entries only contain one element.
// Scrolling to multiple elements simultaneously may lead to unexpected behavior.
for(let entry of entries) {
collapsibleContainer.scrollIntoView()
}
});
resizeObserver.observe(collapsibleContainer);
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.maxHeight){
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
}
});
}
HTML:
<button class="collapsible">
<div class="wrapper">
<h1 class="headline">collapsible</h1>
</div>
</button>
<div class="content-collapse" id="container">
<!-- Remaining content -->
</div>
Unfortunately, ResizeObserver is not compatible with Internet Explorer. However, hopefully you do not need to support that platform.