Sticky TOC-style Navigation with jQuery - Automatic Menu

File Size: 2.49 KB
Views Total: 1804
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Sticky TOC-style Navigation with jQuery - Automatic Menu

Automatic Menu is a small jQuery script to generate a fixed navigation (table of contents) from heading tags in the document. Clicking on the anchor links inside the fixed navigation will jump to the target point of your web page.

How to use it:

1. Build the html structure for the sticky navigation.

<div id="sidebar">
  <ul id="side-menu">
    <li>Menu loading...</li>
  </ul>
</div>

2. Wrap your content into a container named 'content'.

<div id="content">
  <h2>Heading 1</h2>
  <h3>Heading 2</h3>
  <p>Main Content</p>
  ...
</div>

3. Style the sticky navigation.

#sidebar {
  background: #fff;
  width: 280px;
  float: left;
  box-sizing: border-box;
  padding: 5px 20px;
  position: fixed;
  top: 20px;
  font-size: 14px;
  box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.2);
}

#sidebar ul {
  list-style: none;
  padding-left: 0;
  line-height: 1.4;
}

#sidebar ul li { margin: 10px 0; }

#sidebar ul li a {
  color: #8e44ad;
  font-weight: bold;
}

#sidebar ul a { text-decoration: none; }

#sidebar ul ul { padding-left: 15px; }

#sidebar ul ul li a {
  color: #3498db;
  font-weight: normal;
}

4. Include the needed jQuery JavaScript library on the web page.

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script> 

5. Generate a table of content from heading elements in the 'content'.

(function(){
  var id = 'toc';
  var count = 0;
  $("#side-menu").text('');

  $('#content').find('h2').each(function() {

    var $section = $(this);
    var lis = $section.nextUntil("h2", 'h3');

    /*---------------------
     * Create menu item
     *--------------------*/
    var li = $('<li/>');
    var a = $('<a/>', {
      text: $section.text(),
      href: '#' + id + count
    });
    a.appendTo(li);

    /*---------------------
     * Add anchor
     *--------------------*/
    $section.attr('id', id + count);
    count++;

    if (lis.length) {
      var ul = $('<ul/>');
      lis.each(function() {
      /*---------------------
       * Add anchor
       *--------------------*/
        $(this).attr('id', id + count);

        /*---------------------
         * Create menu item
         *--------------------*/
        var lili = $('<li/>');
        var a = $('<a/>', {
          text: $(this).text(),
          href: '#' + id + count
        });
        a.appendTo(lili);
        lili.appendTo(ul);
        count++;
      });
      ul.appendTo(li);
    }

    $('#side-menu').append(li);
  });
})();

This awesome jQuery plugin is developed by EightArmsHQ. For more Advanced Usages, please check the demo page or visit the official website.