How to use Bootstrap Navbar without jQuery

You don’t need jQuery to bring a Bootstrap Navbar to life

295 words · 2 min read

This website uses Bootstrap framework, which is very useful for creating responsive websites. But most of its javascript components aren’t use in my case. It also requires jQuery to run, which is 86KB in size before gzipping. For the only two functions I need—expanding and collapsing the Navbar menu—depending on jQuery seems unnecessary. And it is indeed unnecessary, because those functions can be achieved by some plain vanilla javascript 1% the size of jQuery.

Inspired by Bootstrap without jQuery and Matthew Petroff, I’ve written the script below that expands the menu when a user taps the navbar-toggle button, and collapses the menu when the user taps anywhere in the page (similar to using $(document).on('click',function(){$('.collapse').collapse('hide')}) in Bootstrap with jQuery).

/* Bootstrap Replacement

   Inspired by and modified from Bootstrap without Jquery Project

  var e = document.querySelector(".navbar-toggle");
  var t = document.querySelector(".navbar-collapse");
  var a = e.getAttribute("aria-expanded");

  function getMaxHeight(t) {
    // Source:
    var prevHeight =; = 'auto';
    var maxHeight = getComputedStyle(t).height; = prevHeight;
    t.offsetHeight; // force repaint
    return maxHeight;

/* Open the Menu after clicking the menu button
   Only if the menu is current collapsed that is.

  e.onclick = function() {
    if ( a == "false" ) {
      e.setAttribute('aria-expanded', true); = getMaxHeight(t);

/* Collapse the menu after clicking anywhere, not just the menu button.
   Only if the menu is already expanded, of course.

  document.onclick = function(){
    if ( a == "true" ) {
      e.setAttribute("aria-expanded", false); = getComputedStyle(t).height;

  // Transition Handling
  t.addEventListener("transitionend", function() {

    // Check whether the element is unhidden
    if ( !== '0px') {
      t.classList.add('in'); = 'auto';

    // Get 'aria-expanded' state
    a = e.getAttribute("aria-expanded");

Visit my Github repository for more information.

 Tech    23 Aug, 2016
 Web Development  
Copyright © Peter Y. Chuang 2019

Peter Y. Chuang


Peter Y. Chuang is a novelist, short story writer, and a music critic. When he’s not writing or reading, he’s probably listening to classical music or tinkering with his computers. He uses Linux (current distro of choice: Arch Linux). Read more about his Linux stuff.

You may also like...