Minimalistic JavaScript for Twitter Bootstrap 4 dropdowns
Twitter Bootstrap is a great tool for engineers who are looking to make a decent-looking web page. Although most of its components are CSS-only, a few of them do require JavaScript: jQuery, bootstrap.js and possibly popper.js. In total this amounts to ~300KiB. The only component I've been using on my blog is dropdowns, and that bringing the whole bundle just for it never quite seemed right for me. So, today I replaced it with this little script:
document.querySelectorAll('.dropdown').forEach((dropdown) => {
const toggle = dropdown.querySelector('[data-toggle=dropdown]');
const menu = dropdown.querySelector('.dropdown-menu');
toggle.addEventListener('click', (e) => {
menu.classList.toggle('show');
});
dropdown.addEventListener('focusout', (e) => {
if (e.currentTarget.contains(e.relatedTarget)) {
return;
}
menu.classList.remove('show');
})
});
That's only 311 bytes when minified and works almost just as well. It doesn't do anything smart to try and position the menu within the viewport, nor it provides the JS API that the Bootstrap component does, but I don't actually need that on my blog.
Hope it comes handy to someone