
Table of contents
Planted:
Tended:
Status: decay
Hits: 1298
Intended Audience: Front-end developers
How to create a table of contents.
Requirements
- ▪ a link for each section of content
- ▪ clicking a link scrolls the page to the related section
- ▪ when a section is in the viewport, its link is highlighted
- ▪ links are always in viewport, regardless of how far the user has scrolled
Initial render
We start by creating the elements for the initial render.
Make body
a flex container and add two children:
- ▪
ul
on the left for rendering the links and - ▪
main
on the right for rendering each section of content.
Sticky
To keep the links in the viewport while the user is scrolling, set ul
to position: sticky; top: 0;
.
By default, a flex container stretches its children to 100%
of its height.
This means body
and ul
will be the same height.
For position: sticky
to work, the element's height needs to be less than the scrolling element's height.
ul
height needs to be less than body
height.
Therefore we need to prevent stretching by setting ul
to align-self: flex-start
.
Observe
To highlight a link when its section scrolls into the viewport, we can use the Intersection Observer. In its options object:
- ▪ don't set a value for the
root
property so the default (the viewport) is used, - ▪ set
threshold: 0
to trigger the callback when1px
of a target element intersects the root and - ▪ set
rootMargin: "-50% 0px"
to make the intersection area1px
height in the middle of the viewport.
Observe each section
.
When one is scrolled into the middle of the viewport, the callback will be executed.
Use the callback to update which link is highlighted.
Feedback
Have any feedback about this note or just want to comment on the state of the economy?
Where to next?
