Skip to content

Instantly share code, notes, and snippets.

@smagch
Created November 26, 2019 04:14
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 smagch/46140c3b2358288340deeaaee4247365 to your computer and use it in GitHub Desktop.
Save smagch/46140c3b2358288340deeaaee4247365 to your computer and use it in GitHub Desktop.
open/collapse for an element with `height: auto`
<html>
<head>
<style>
.item {
display: block;
overflow: hidden;
}
.head {
height: 30px;
line-height: 30px;
background: tomato;
color: white;
}
.content {
opacity: 0;
visibility: hidden;
border: 1px solid #eee;
height: 0;
transition: all 0.3s;
overflow: hidden;
}
.content.active {
opacity: 0;
visibility: visible;
height: auto;
}
</style>
</head>
<body>
<div class="item">
<div class="head">head</div>
<div class="content">body</div>
</div>
hoge
<script>
const item = document.querySelector('.item');
const head = document.querySelector('.head');
const content = document.querySelector('.content');
head.addEventListener('click', () => {
content.classList.toggle('active');
if (content.classList.contains('active')) {
const height = content.getBoundingClientRect().height;
content.style.height = '0px';
window.requestAnimationFrame(() => {
content.style.height = `${height}px`;
content.style.opacity = 1;
});
} else {
content.style.height = '';
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment