Sections

Scrollspy

Update a set of links based on the scroll position of the page (or element).

Usage

Each link within the element being spyed upon must have a resolvable target, meaning that the href attribute must point to a element that exists on the page. For example, <a href="#heading-1">Heading 1</a> could reference the element <h1 id="heading-1"></h1>.

Via data attributes

Scrollspy behavior can be initialized by adding data-spy="scroll" to the element you want to spy on.

<ul class=list-unstyled" data-spy="scroll">...</ul>

If data attributes are used, you will need to ensure that the allow unsage HTML setting is enabled within Guide.

Via JavaScript

The Scrollspy plugin can be initialized on a given element using JavaScript:

var nav = document.querySelector('.my-nav');
if (nav) {
  new Scrollspy(nav);
}

When successfully initialized, links within your target element will be updated automatically with the active class name moved from one item to the next based on their associated targets. To use the plugin with links that are rendered using JavaScript,initialize the plugin on the element after the rendering is complete:

Example

  • <div class="row">
      <div class="col-6 md:col-4 lg:col-3">
        <nav id="navigation-1" class="navbar flex-column" data-scroll-element="#scroll-element-1"></nav>
      </div>
      <div class="col">
        <div id="scroll-element-1"> ... </div>
      </div>
    </div>
    
    <script type="text/javascript">
      ready(function() {
        var nav = document.getElementById('navigation-1');
        if (nav) {
          nav.addEventListener('tableOfContents.render', function() {
            new Scrollspy(nav);
          });
    
          new TableOfContents(nav, {
            hierarchical: true,
            parentElement: '#scroll-element-1',
            template: 'table-of-contents'
          });
        }
      });
    </script>
    
    <script type="text/html" id="tmpl-table-of-contents">
      <% if (items.length) { %>
        <ul class="nav nav-pills flex-column">
          <% items.forEach(function(item) { %>
            <li class="nav-item">
              <a class="nav-link" href="<%= item.html_url %>">
                <%= item.name %>
              </a>
            </li>
          <% }); %>
        </ul>
      <% } %>
    </script>

Options

Options can be passed via data attributes or JavaScript.

For data attributes, append the option name to data-.

Name Type Default Description
offset number 0 Pixels to offset from top when calculating position of scroll.
scrollElement string
DOM element
window The scrolling element that should be observed.
activeClass string is-active Class name(s) to apply to the active link.

Events

There are no events emitted by this plugin.