DailyJS
Published in

DailyJS

Mimicking Bootstrap’s Collapse with Vanilla Javascript

Photo by Evan Kirby from UnSplash

How does Bootstrap do it?

<!-- target element to collapse/expand -->
<div class="collapse">
/* your content here */
</div>
<script>
$('.collapse').collapse('toggle')
</script>
<!-- data-* attributes set this button up as a trigger -->
<button data-toggle="collapse" data-target=".collapse">Click</button>
<!-- target element to collapse/expand -->
<div class="collapse">
/* your content here */
</div>

Our implementation

The Styles

*, ::after, ::before {
box-sizing: border-box;
}
.collapse {
display: block;
max-height: 0px;
overflow: hidden;
transition: max-height .5s cubic-bezier(0, 1, 0, 1);
&.show {
max-height: 99em;
transition: max-height .5s ease-in-out;
}
}

The JavaScript

// map our commands to the classList methods
const fnmap = {
'toggle': 'toggle',
'show': 'add',
'hide': 'remove'
};
const collapse = (selector, cmd) => {
const targets = Array.from(document.querySelectorAll(selector));
targets.forEach(target => {
target.classList[fnmap[cmd]]('show');
});
}

Data Attribute Triggers and Events

// Grab all the trigger elements on the page
const triggers = Array.from(document.querySelectorAll('[data-toggle="collapse"]'));
// Listen for click events, but only on our triggers
window.addEventListener('click', (ev) => {
const elm = ev.target;
if (triggers.includes(elm)) {
const selector = elm.getAttribute('data-target');
collapse(selector, 'toggle');
}
}, false);

Summary

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
David Atchley

Founder @tandemly. Full-stack narwhal and Javascript ❤️’er. Drip coffee addict and wanna-be designer. (http://tandem.ly)