Bootstrap 4 Scrollspy

The Scrollspy plugin, that is, the auto-update navigation plugin, automatically updates the corresponding navigation target based on the scrollbar position. Its basic implementation is as you scroll.


How to Create Scrollspy

The following example demonstrates how to create scrollspy:

Example

<!--Scrollable area--> <body data-spy="scroll" data-target=".navbar" data-offset="50"> <!-- The navbar - The <a> elements are used to jump to a section in the scrollable area --> <nav class="navbar navbar-expand-sm bg-dark navbar-dark fixed-top"> ... <ul class="navbar-nav"> <li><a href="#section1">Section 1</a></li> ... </nav> <!--First section content--> <div id="section1"> <h1>Section 1</h1> <p>Try to scroll this page and look at the navigation bar while scrolling!</p> </div> ... </body>

Try it »

Example Analysis

Add to the element you want to monitor (usually body)data-spy="scroll" 。

Then adddata-targetan attribute, whose value is the navbar's id or class (.navbar). This makes it connect to the scrollable area.

Note that the id on the scrollable item element (<div id="section1">) must match the link options on the navbar (<a href="../index.html">)。

Optionaldata-offsetattribute is used to calculate the offset pixels from the top when computing the scroll position. The default is 10 px.

Set relative positioning:The element using data-spy="scroll" needs to have its CSSpositionproperty set to "relative" to work.

The following example sets up vertical scrollspy:

Example

<body data-spy="scroll" data-target="#myScrollspy" data-offset="1"> <div class="container-fluid"> <div class="row"> <nav class="col-sm-3 col-4" id="myScrollspy"> <ul class="nav nav-pills flex-column"> <li class="nav-item"> <a class="nav-link active" href="#section1">Section 1</a> </li> ... </ul> </nav> <div class="col-sm-9 col-8"> <div id="section1"> <h1>Section 1</h1> <p>Try to scroll this page and look at the navigation list while scrolling!</p> </div> ... </div> </div> </div> </body>

Try it »
Other extensions