Skip to content

Instantly share code, notes, and snippets.

@Tombarr
Created February 16, 2025 05:52
Show Gist options
  • Save Tombarr/8699c4e2fd003eaed7f527a05a7fa460 to your computer and use it in GitHub Desktop.
Save Tombarr/8699c4e2fd003eaed7f527a05a7fa460 to your computer and use it in GitHub Desktop.
Bootstrap Collapse without importing Bootstrap JS
document.querySelectorAll('[data-bs-toggle="collapse"]').forEach(button => {
button.addEventListener("click", (event) => {
event.preventDefault();
let targetSelector = button.getAttribute("data-bs-target");
let target = document.querySelector(targetSelector);
if (target) {
let isCollapsed = target.classList.contains("show");
if (isCollapsed) {
collapseElement(target);
} else {
expandElement(target);
}
}
});
});
document.querySelectorAll('[data-bs-dismiss="collapse"]').forEach(button => {
button.addEventListener("click", () => {
let targetSelector = button.getAttribute("data-bs-target");
let target = document.querySelector(targetSelector);
if (target) collapseElement(target);
});
});
function collapseElement(element) {
element.style.height = element.scrollHeight + "px";
setTimeout(() => {
element.style.height = "0px";
element.classList.remove("show");
}, 10);
}
function expandElement(element) {
element.style.height = "auto";
let height = element.scrollHeight + "px";
element.style.height = "0px";
element.classList.add("show");
setTimeout(() => {
element.style.height = height;
}, 10);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment