Drawer Example
by amindunited
HTML
<div class='container'>
<div class="box">
<div class="box-content">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>
</div>
</div>
<button>
toggle
</button>
CSS
.box {
border: solid 1px grey;
margin: 16px;
box-shadow: 0px 9px 40px rgba(0, 0, 0, 0.16);
overflow: hidden;
transition: max-height 0.8s ease-out, color 0.8s ease-out;
}
.box.closed {
border: none;
padding: 0;
max-height: 0px;
color: rgba(0, 0, 0, 0);
}
.box-content {
padding: 16px 32px;
}
JavaScript
document.addEventListener('DOMContentLoaded', (event) => {
run();
});
const createDrawer = (el, trigger) => {
// Unhide the element and get it's height, then hide it again
el.classList.remove('closed');
const drawerHeight = getComputedStyle(el).getPropertyValue('height');
el.classList.add('closed');
//
const clickHandler = () => {
// Prevent the user from multi triggering
trigger.removeEventListener('click', clickHandler);
// If it's allready closed, remove the 'closed' class, and set the height
if ( [...el.classList].includes('closed') ) {
el.classList.remove('closed');
el.style.maxHeight = drawerHeight;
const transitionEndFn = () => {
trigger.addEventListener('click', clickHandler);
};
el.addEventListener('transitionend', transitionEndFn);
}
// If it's open set the height to 0, and wait for the animation to stop before removing the class
// this reduces conflict with SOME css layout properties
else {
el.style.maxHeight = '0px';
const transitionEndFn = () => {
el.removeEventListener('transitionend', transitionEndFn);
el.classList.add('closed');
trigger.addEventListener('click', clickHandler);
};
el.addEventListener('transitionend', transitionEndFn);
}
};
trigger.addEventListener('click', clickHandler);
};
const run = () => {
const box = document.querySelector('.box');
const butt = document.querySelector('button');
createDrawer(box, butt);
};