Easy Tutorial
❮ Bootstrap4 Carousel Bootstrap4 Makeawebsite ❯

Bootstrap 4 Scrollspy

The Scrollspy plugin, which automatically updates the navigation plugin, updates the corresponding navigation target based on the position of the scrollbar. Its basic implementation is as you scroll.


How to Create Scrollspy

The following example demonstrates how to create a scrollspy:

Example

<!-- Scrollable area -->
<body data-spy="scroll" data-target=".navbar" data-offset="50">

<!-- The navbar - The &lt;a&gt; 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>

Example Analysis

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

Then add the data-target attribute, whose value is the id or class (.navbar) of the navigation bar. This connects it to the scrollable area.

Note that the id of the scrollable item element (e.g., <div id="section1">) must match the link option in the navigation bar (e.g., <a href="#section1">).

The optional data-offset attribute is used to calculate the scroll position with an offset from the top. The default is 10px.

Setting Relative Positioning: Elements using data-spy="scroll" need to have their CSS position property 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>
❮ Bootstrap4 Carousel Bootstrap4 Makeawebsite ❯