Skip to content

Instantly share code, notes, and snippets.

@alexmacarthur
Last active November 23, 2020 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexmacarthur/30bb53063f7b6cd0b919547370b5a5b1 to your computer and use it in GitHub Desktop.
Save alexmacarthur/30bb53063f7b6cd0b919547370b5a5b1 to your computer and use it in GitHub Desktop.
Rudimentary slideToggle() in Vanilla JS
<!--
Rather than using the "max-height hack" to animate the opening of a box,
you can achieve virtually the same effect using an approach like below. It
doens't require writing any CSS itself, and handles dynamic contents well.
-->
<div class="box" id="box" style="height: 0;">
<div class="box-container">
<span>It's a box!</span>
</div>
</div>
<script>
const box = document.getElementById('box');
const button = document.getElementById('button');
const slideToggle = function (el) {
el.style.height = "";
const isClosing = el.dataset.slideState == "open";
const fromHeight = isClosing ? el.scrollHeight : 0;
const toHeight = isClosing ? 0 : el.scrollHeight;
el.style.transitionProperty = 'height';
el.style.transitionDuration = '.25s';
el.style.height = `${fromHeight}px`;
requestAnimationFrame(() => {
requestAnimationFrame(() => {
el.style.height = `${toHeight}px`;
el.dataset.slideState = isClosing ? "closed" : "open";
})
});
}
button.addEventListener('click', () => {
slideToggle(box);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment