Last active
November 23, 2020 13:56
-
-
Save alexmacarthur/30bb53063f7b6cd0b919547370b5a5b1 to your computer and use it in GitHub Desktop.
Rudimentary slideToggle() in Vanilla JS
This file contains 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
<!-- | |
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