Sections

Scrollspy

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

In this article

Example

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.

  • <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>

To use the plugin with links that are rendered using JavaScript, initialize the plugin on the element after rendering is complete.

Usage

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 unsafe HTML setting is enabled within Guide.

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

<nav class="custom-nav">...</nav>

<script type="text/javascript">
  ready(function() {
    var nav = document.querySelector('.custom-nav');
    if (nav) {
      new Scrollspy(nav);
    }
  });
</script>

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">First heading</a> could reference the element <h1 id="heading-1">First heading</h1>.

Options

Options can be passed via data attributes or JavaScript.

For data attributes, append the option name to data- and use kebab case instead of camel case.

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.