scrollspy bootstrap 4

Scrollspy in Bootstrap 4

To implement scrollspy in Bootstrap 4, you can use the data-spy attribute along with data-target and data-offset attributes. The data-spy attribute is used to activate scrollspy on an element, while data-target specifies the target element to use as the scrollable area. The data-offset attribute can be used to set the offset of the scrollspy.

Here's an example of how to use scrollspy in Bootstrap 4:

<body data-spy="scroll" data-target="#navbar-example" data-offset="50">
  <div id="navbar-example">
    <ul class="nav">
      <li><a href="#section1">Section 1</a></li>
      <li><a href="#section2">Section 2</a></li>
      <li><a href="#section3">Section 3</a></li>
    </ul>
  </div>
  <div data-spy="scroll" data-target="#navbar-example" data-offset="0">
    <h4 id="section1">Section 1</h4>
    <p>Content for section 1</p>
    <h4 id="section2">Section 2</h4>
    <p>Content for section 2</p>
    <h4 id="section3">Section 3</h4>
    <p>Content for section 3</p>
  </div>
</body>

In this example, the data-spy attribute is set to "scroll" to activate scrollspy, and the data-target attribute is set to "#navbar-example" to specify the target element. The data-offset attribute is set to "50" to provide an offset for the scrollspy.

By using these attributes, you can enable scrollspy in Bootstrap 4 to automatically update the active navigation links based on scroll position.