Bootstrap sidebar nav like on components site

user3631654 picture user3631654 · Apr 29, 2016 · Viewed 6.9k times · Source

I would like to build a sidebar navigation that behavaves exactly like on the bootsrap components page with the difference that it should appear on the left side: http://getbootstrap.com/components/

Requirements:

  • Set active class related to last viewed heading
  • Collapse/Expand childrens

Is there a predefined way realize this?

Answer

Randy picture Randy · Apr 29, 2016

http://afeld.github.io/bootstrap-toc/

You can find the exact table of contents Bootstrap is using on that page.

Usage

On top of the normal Bootstrap setup (see their Getting Started guide), you will need to include the Bootstrap Table of Contents stylesheet and JavaScript file.

<!-- add after bootstrap.min.css -->
<link rel="stylesheet" href="https://cdn.rawgit.com/afeld/bootstrap-toc/v0.3.0/dist/bootstrap-toc.min.css">
<!-- add after bootstrap.min.js -->
<script src="https://cdn.rawgit.com/afeld/bootstrap-toc/v0.3.0/dist/bootstrap-toc.min.js"></script>

Via data attributes

Simplest.

Create a <nav> element with a data-toggle="toc" attribute.

<nav id="toc" data-toggle="toc"></nav>

You can put this wherever on the page you like. Since this plugin leverages Bootstrap’s Scrollspy plugin, you will also need to add a couple attributes to the <body>:

<body data-spy="scroll" data-target="#toc">

Via JavaScript

If you need customization.

If you prefer to create your navigation element another way (e.g. within single-page apps), you can pass a jQuery object into Toc.init().

$(function() {
var navSelector = '<something>';
var $myNav = $(navSelector);
Toc.init($myNav);
  $('body').scrollspy({
    target: navSelector
  });
});

See the Scrollspy documentation for more information about initializing that plugin.

Options

When calling Toc.init(), you can either pass in the jQuery object for the <nav> element (as seen above), or an options object:

Toc.init({
  $nav: $('#myNav'),
  // ...
});

All options are optional, unless otherwise indicated.