Bootstrap ScrollSpy


In this tutorial you will learn how to create scrollspy with Bootstrap.

Creating ScrollSpy with Bootstrap

The Bootstrap scrollspy is a navigation mechanism that automatically highlights the nav links based on the scroll position to indicate the visitor where they are currently on the page.

The scrollspy will make your web page more elegant and accessible, if you’re using the bookmark links for directing the visitors to the different sections of a page that has a huge amount of content.

Scrollspy has the following requirements to function properly:

  • It must be used on a Bootstrap nav, or list group component.
  • You must apply the style position: relative; on the element you’re spying on, which is usually the <body> element. But, if you’re spying a <div> or any element other than the <body> be sure to additionally apply a height and overflow-y: scroll; on it.
  • Anchors (<a>) are required and must point to an element with that id.

Here’s an example of a scrollspy using the list group. Let’s try it out and see how it works:

Example

<body data-bs-spy="scroll" data-bs-offset="15" data-bs-target="#myScrollspy">
    <div class="container">
        <div class="row">
            <div class="col-sm-3" id="myScrollspy">
                <div class="list-group">
                    <a class="list-group-item list-group-item-action active" href="#section1">Section One</a>
                    <a class="list-group-item list-group-item-action" href="#section2">Section Two</a>
                    <a class="list-group-item list-group-item-action" href="#section3">Section Three</a>
                </div>
            </div>
            <div class="col-sm-9">
                <div id="section1">
                    <h2>Section One</h2>
                    <p>This is section one content...</p>
                </div>
                <hr>
                <div id="section2">
                    <h2>Section Two</h2>
                    <p>This is section two content...</p>
                </div>
                <hr>
                <div id="section3">
                    <h2>Section Three</h2>
                    <p>This is section three content...</p>
                </div>
            </div>
        </div>
    </div>
</body>

Leave a Reply

Your email address will not be published. Required fields are marked *