Scrollspy example for mobile

What's this?

This is an example of scrollspy for mobile.

Scrollspy is often shown as table of contents in sidebars. But, for mobile, we rarely see scrollspy because sidebars are usually not generated.

This is a proposal of scrollspy for mobile which is fixed on the top, shows only single line and changes it on scrolling.

Motivation for this page

I was impressed by Intersection Observer を用いた要素出現検出の最適化("Optimization of detect of element appearance by Intersection Observer". You can see similar article in English here: Intersection Observer API) and wanted to use it, then, chose scrollspy as a material.

Smooth scroll by CSS

CSS has scroll-behavior propery and by setting the value to smooth such as:

body {
      scroll-behavior: smooth;

browsers run smooth scroll automatically. This page also uses the feature.

Firefox(except for on iOS) supports it as of . Try this page on Firefox.

See also: scroll-behavior - CSS | MDN

Sticky poisitioning only by CSS(position: sticky

The navigation by scrollspy in this page is under the page title at first, and after scrolling, becomes fixed at the top of the page.

This kind of feature is often implemented by combination of JavaScript and CSS. But it was done by only CSS in this page. By setting position property to sticky such as:

nav {
      position: sticky;

the behavior as said above is achieved.

As of , Firefox and Safari support the property.

See also: CSS "position: sticky" - Introduction and Polyfills

CSS custom properties(CSS variables)

The height of scrollspy is defined by a CSS custom property although you cannot see it directly in the page.

Each section has top padding whose height is the same to scrollspy's. Leaks of setting is prevented by managing the hight by a shared variable.

Now Chrome and Safari support CSS custom properties as well as Firefox.

See also: CSS Variables: Why Should You Care?  |  Web  |  Google Developers

Source code

Source code of this page is hosted by GitLab.

Source code:KitaitiMakoto/scrollspy-example

©Kitaiti Makoto