Created
February 16, 2025 05:52
-
-
Save Tombarr/8699c4e2fd003eaed7f527a05a7fa460 to your computer and use it in GitHub Desktop.
Bootstrap Collapse without importing Bootstrap JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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