Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand/collapse mobile navbar without JavaScript

On mobile devices, Bootstrap 3 by default reduces the navigation bar (navbar) to a hamburger icon. When clicking the hamburger, a JavaScript toggles the display of the navigation menu items - either expanding or collapsing the navbar. But

how to toggle the bootstrap mobile navbar collapse/expand without requiring JavaScript?

If this were possible, it would have nice performance advantages: users can already navigate before JavaScript is executed (a good plus on flaky mobile connections), and smaller projects may be able to drop the dependency on jQuery + bootstrap javascript entirely, saving around 45k on first page load. Plus, the site becomes more robust in case of JS errors - at least the page navigation stays usable.

Alternatively, one could re-implement the bootstrap JS without jQuery dependency - done here for the navbar.

For reference, this is what the static navbar top example looks like in mobile mode:

Bootstrap 3 mobile navbar expanded

like image 470
flexponsive Avatar asked Jul 19 '15 22:07

flexponsive


1 Answers

Yes, it's possible!

Getting the BS3 mobile navbar to toggle without JavaScript

  1. creating a hidden checkbox that contains the navbar state (expand if checked)

  2. changing the navbar button to a label for this invisible checkbox

  3. use the CSS General Sibling Selector to toggle display of the navbar.

How to change CSS attributes without JavaScript was discussed before on SO, and the principle shown there 1. Applying this bootstrap is straightforward.

Try the Live demo thanks to rawgit or see it in production on flexponsive

A full demo is available on Github project bs3-navbar-collapse-without-javascript.

Browser Support

  • the CSS general sibling selector is widely supported
  • successfully tested in mobile: Android 5 and iOS 8
  • also works on desktop: Chrome 43 and Firefox 38

Limitations

  • dropdowns still require JS, if you decide to use them

Steps in detail

First, custom CSS you need to add:

/* show the collapse when navbar toggle is checked */
#navbar-toggle-cbox:checked ~ .collapse {
    display: block;
}

/* the checkbox used only internally; don't display it */
#navbar-toggle-cbox {
  display:none
}

Then change the navbar HTML as follows:

<!-- insert checkbox -->
<input type="checkbox" id="navbar-toggle-cbox">
<!-- change the "hamburger" icon from being a button to a label for checkbox -->
<div class="navbar-header">
 <label for="navbar-toggle-cbox" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
    <span class="sr-only">Toggle navigation</span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
  </label>
<!-- end label not button -->
like image 98
flexponsive Avatar answered Sep 28 '22 18:09

flexponsive