Brad Woods Digital Garden

Notes / JavaScript / Web API / Intersection Observer / Table of contents

The Warhammer 40k Adeptus Mechanicus symbol

Table of contents

    A web page table of contents wireframe

    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.
    An isometric view of the DOM. Showing the viewport, a list of links on the left and a list of sections on the right.

    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.

    An isometric view of the DOM. Showing the viewport, a list of links on the left and a list of sections on the right.

    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 when 1px of a target element intersects the root and
    • set rootMargin: "-50% 0px" to make the intersection area 1px height in the middle of the viewport.
    A wireframe of the viewport showing 2 shaded areas at the top and bottom

    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?

    JavaScript
    Web API
    Arrow pointing downYOU ARE HERE
    A Johnny Cab pilot