Skip to content

Instantly share code, notes, and snippets.

@denisso
Last active May 24, 2023 11:18
Show Gist options
  • Save denisso/ec3fe208391710c53a20740ec7cfd932 to your computer and use it in GitHub Desktop.
Save denisso/ec3fe208391710c53a20740ec7cfd932 to your computer and use it in GitHub Desktop.
Acordion - DropDown with smooth offset
<!-- https://codepen.io/den4ik_rus/pen/RweqdYK -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
.box {
width: 500px;
margin: 0 auto;
}
.item {
padding: 1rem;
border: 2px solid black;
user-select: none;
}
.item:first-child {
cursor: pointer;
}
.item+.item {
margin-top: .5rem;
}
.drop-down {
position: relative;
overflow: hidden;
height: 0;
transition: height 1s;
}
.drop-down.show {
height: auto;
}
.drop-down.show .content {
position: static;
}
.drop-down .content {
position: absolute;
width: 100%;
bottom: 0;
}
</style>
</head>
<body>
<div class="box">
<div class="item">
<div class="title">First Line (Click switch DropDown show)</div>
<div class="drop-down">
<div class="content">Lorem ipsum dolor sit amet consectetur adipisicing elit. Fugiat commodi consequuntur, nostrum hic maiores similique. Molestiae deleniti expedita ex, doloribus sequi deserunt, officia obcaecati ratione numquam veniam hic aut totam.</div>
</div>
</div>
<div class="item">
<div class="title">Second Line</div>
</div>
</div>
<script>
const item = document.querySelector(".item");
const handler = () => {
const dropDown = item.querySelector(".drop-down");
const content = item.querySelector(".content");
const heightContent = content.getBoundingClientRect().height + "px";
let show = false;
return (e) => {
switch (e.type) {
case "click":
{
if (!show) {
show = true
dropDown.style.height = heightContent;
} else {
show = false
if (dropDown.classList.contains("show")) {
dropDown.style.height = heightContent;
setTimeout(() => {
dropDown.classList.remove("show");
dropDown.removeAttribute("style");
}, 0);
}
else{
dropDown.removeAttribute("style");
}
}
}
break;
case "transitionend":
{
if (show) {
dropDown.classList.add("show");
dropDown.removeAttribute("style");
}
}
break;
default:
}
}
}
item.onclick = item.ontransitionend = handler();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment