Toggle Bootstrap collapsible state by device screen size

How to turn on/off Bootstrap’s collapse function based on window.innerWidth

function toggleCollapsibility(container) {
    // Default to disabled
    let find = 'collapse', replace = 'collapse-disabled'

    // We only want collapse on smaller devices
    if (window.innerWidth < 992) {
        // Flip to enabled
        [find, replace] = [replace, find]
    }

    document.querySelectorAll(`${container} [data-bs-toggle="${find}"]`).forEach((element) => {
        element.dataset.bsToggle = replace
    })
}

Example usage

window.addEventListener('resize', (event) => {
    toggleCollapsibility('#offcanvas-menu')
})
document.addEventListener('readystatechange', (event) => {
    if (document.readyState == 'interactive') {
        window.dispatchEvent(new Event('resize'))
    }
})

Example markup

<nav class="list-group">
	<a href="parent" class="list-group-item collapsed" data-bs-toggle="collapse" data-bs-target="#item-1" aria-expanded="false">Parent</a>
	<div class="list-group collapse" id="item-1">
		<a href="parent/child" class="list-group-item collapsed" data-bs-toggle="collapse" data-bs-target="#item-2" aria-expanded="false">Child</a>
		<div class="list-group collapse" id="item-2">
			<a href="parent/child/grandchild" class="list-group-item">Grandchild</a>
			<a href="parent/child" class="list-group-item text-decoration-underline">Show All Child</a>
		</div>
		<a href="parent" class="list-group-item text-decoration-underline">Show All Parent</a>
	</div>
</nav>

Leave a Reply

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