Scrollspy
A menu of links to sections on the same page marks the one you are reading as you scroll. For a table of contents, a row of tabs under the header, or a side menu.
Try it
Add data-momo-scrollspy to anything that holds links to #sections. Scroll this page, or click a link: the row below follows.
<nav class="tabs tabs-pill" data-momo-scrollspy aria-label="On this page" id="sp-nav" style="margin-bottom: 0">
<a class="tab" href="#try-it">Try it</a>
<a class="tab" href="#how-it-decides">How it decides</a>
<a class="tab" href="#styling-the-current-link">Styling</a>
<a class="tab" href="#good-to-know">Good to know</a>
<a class="tab" href="#reference">Reference</a>
</nav><nav class="tabs tabs-pill" data-momo-scrollspy aria-label="On this page">
<a class="tab" href="#shipping">Shipping</a>
<a class="tab" href="#returns">Returns</a>
<a class="tab" href="#contact">Contact</a>
</nav>
<h2 id="shipping">Shipping</h2> …
<h2 id="returns">Returns</h2> …To keep the row in view while the page scrolls, make it sticky: class="sticky top-0" (see Fixed, sticky & frosted).
How it decides
- The current section is the last one whose heading has passed the top of the screen.
- A click on a link glides to its section. People who asked their device for less motion get a plain jump, and
data-momo-scrollspy="instant"turns the glide off for everyone. - A sticky header is taken into account: set
scroll-padding-topon<html>to its height, and both the marking and jumps to a section stop below it. - At the very bottom of the page the last link is marked, even when its section is too short to reach the top.
- Only links to this page count. Links to other pages in the same menu are left alone.
html { scroll-padding-top: 5rem; } /* the height of your sticky header */Styling the current link
The current link gets .is-active and aria-current="location". Tabs, the site sidebar's "On this page" list and list groups already have a look for it. For your own links:
.my-toc a.is-active { font-weight: 700; color: var(--momo-ink); }Good to know
- It follows the page's own scrolling, not a box that scrolls inside the page.
- Sections added later are found the next time the page scrolls. A menu added later is picked up by itself.
- It only reads positions while the page moves, once per frame, so a long page stays smooth.
Reference
| Attribute / class | What it does |
|---|---|
data-momo-scrollspy | On a menu of #section links: marks the one in view |
.is-active, aria-current="location" | Put on the current link |
.site-toc | The site sidebar's "On this page" list does this without the attribute |
scroll-padding-top on <html> | The height of a sticky header, so sections stop below it |