Sitemap

Bootstrap Accordion scroll issue

2 min readSep 29, 2023

--

The issue was: if you click to show an accordion item at the bottom of the screen, the item would open off screen.

Press enter or click to view image in full size

Get David Buchs’s stories in your inbox

Join Medium for free to get updates from this writer.

The solution is a script that listens for the shown.bs.collapse event and scrolls to the correct position depending on the height of the item and the current scroll position.

<script>
// Accordion items at the bottom of the screen open off the screen.
// This scrolls so that the whole item is visible.
document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('.accordion-item').forEach(function (item) {

// Listen for shown.bs.collapse event. Different from show.bs.collapse
// Needs to be shown.bs.collapse otherwise the item has no height.
item.addEventListener('shown.bs.collapse', function () {
// Get the height of the item content
var itemHeight = this.scrollHeight;

// if itemHeight is bigger than window, then just scroll to top
if (itemHeight >= window.innerHeight) {
window.scrollTo({
top: this.offsetTop,
behavior: 'smooth'
});
// if the item is lower than it would be when we scroll down, then scroll
// We use (window.innerHeight - itemHeight)/2 so that we can see that there are
// items below the current item.
} else if (this.offsetTop - (window.innerHeight - itemHeight) / 2 > window.scrollY) {
window.scrollTo({
top: this.offsetTop - (window.innerHeight - itemHeight) / 2,
behavior: 'smooth'
});
}

});
});
});
</script>
Press enter or click to view image in full size

--

--