Get up to 80 % extra points for free! More info:

Lesson 20 - Bootstrap - Scrollspy

In the previous lesson, Bootstrap - Popovers, we introduced Popovers. Only the last 2 Bootstrap components are left to be discussed. In today's tutorial of this CSS framework, we're going to talk about the first one - Scrollspy.

Scrollspy

Scrollspy is a component that allows us to see which part of the page we are in, according to the position of our scrollbar. Our position is shown in the Navigation or List Group components.

Scrollspy needs the position of the scrolling element, most often <body>', to be set to `position: relative. If we use Scrollspy on any other element, its height should, of course, be defined and overflow-y: scroll set, so that the scrollbar would show up :) We use the <a> elements only in the navigation. The active item of the navigation will be marked with the .active class automatically, however we must mark the first one manually.

Examples

We'll showcase Scrollspy on different components.

Navbar

First let's show the component on a navbar:

<body data-spy="scroll" data-target="#navbar-example" data-offset="70" style="position: relative">
    <nav id="navbar-example" class="navbar navbar-light bg-light sticky-top">
        <a class="navbar-brand" href="#">Navigation</a>
        <ul class="nav nav-pills">
            <li class="nav-item">
                <a class="nav-link active" href="#lorem">Lorem ipsum</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#duis">Duis semper</a>
            </li>
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Next</a>
                <div class="dropdown-menu">
                    <a class="dropdown-item" href="#fusce">Fusce erat eros</a>
                </div>
            </li>
        </ul>
    </nav>
    <div>
        <h4 id="lorem">Lorem ipsum</h4>
        <p>...</p>
        <h4 id="duis">Duis semper</h4>
        <p>...</p>
        <h4 id="fusce">Fusce erat eros</h4>
        <p>...</p>
    </div>
</body>

We assign the attributes data-spy="scroll" and data-target with the navigation selector to the element which we want to scroll through, most often <body>. Scrollspy is ready now. To make the binding between the navigation and the content work, the links must point to the IDs of the corresponding elements of the content we want to spy on. Of course, we can't forget to link the Bootstrap's JavaScript as well. We keep the navigation sticked to the top using the .sticky-top class.

The result in the browser:

Scrollspy in Bootstrap
scrollspy_navi­gation.html

Try to scroll now, the navigation will switch depending on what part of the document you're currently in. Scrollspy ignores invisible elements.

Multilevel navigation

Scrollspy can make the parent of the navigation element active as well, if the navigation is multilevel. Let's try it:

<body data-spy="scroll" data-target="#navbar-example" data-offset="70" style="position: relative">
    <div class="row">
        <div class="col-4">
            <nav id="navbar-example" class="navbar navbar-light bg-light sticky-top">
                <a class="navbar-brand" href="#">Navigation</a>
                <nav class="nav nav-pills flex-column">
                    <a class="nav-link active" href="#lorem">Lorem ipsum</a>
                    <nav class="nav nav-pills flex-column">
                        <a class="nav-link ml-3 my-1" href="#aenean">Aenean a condimentum</a>
                        <a class="nav-link ml-3 my-1" href="#vivamus">Vivamus</a>
                    </nav>
                    <a class="nav-link" href="#duis">Duis semper</a>
                    <a class="nav-link" href="#fusce">Fusce erat eros</a>
                    <nav class="nav nav-pills flex-column">
                        <a class="nav-link ml-3 my-1" href="#mauris">Mauris tempor</a>
                    </nav>
                </nav>
            </nav>
        </div>

        <div class="col-8">
            <h4 id="lorem">Lorem ipsum</h4>
            <p>...</p>
            <h5 id="aenean">Aenean a condimentum</h5>
            <p>...</p>
            <h5 id="vivamus">Vivamus</h5>
            <p>...</p>
            <h4 id="duis">Duis semper</h4>
            <p>...</p>
            <h4 id="fusce">Fusce erat eros</h4>
            <p>...</p>
            <h5 id="mauris">Mauris tempor</h5>
            <p>...</p>
        </div>
    </div>
</body>

The live demo:

Scrollspy in Bootstrap
scrollspy_mul­tilevel.html

List group

We'll finish the examples by creating a vertical navigation using the List Group component.

<body data-spy="scroll" data-target="#list-example" data-offset="70" class="scrollspy-example" style="position: relative">
    <div class="row">
        <div class="col-4">
            <div id="list-example" class="list-group sticky-top">
                <a class="list-group-item list-group-item-action active" href="#lorem">Lorem ipsum</a>
                <a class="list-group-item list-group-item-action" href="#duis">Duis semper</a>
                <a class="list-group-item list-group-item-action" href="#fusce">Fusce erat eros</a>
            </div>
        </div>

        <div class="col-8">
            <h4 id="lorem">Lorem ipsum</h4>
            <p>...</p>
            <h4 id="duis">Duis semper</h4>
            <p>...</p>
            <h4 id="fusce">Fusce erat eros</h4>
            <p>...</p>
        </div>
    </div>
</body>

The live demo:

Scrollspy in Bootstrap
scrollspy_lis­t_group.html

JavaScript

Again, we can control the component in JavaScript.

Initialization

Instead of using the data attribute we can perform the initialization by calling the scrollspy() method.

$('body').scrollspy({ target: '#navbar-example' });

Properties

Using the data-offset data attribute or the offset JS property we can specify the offset from the top edge of the screen from which the position of the scrollbar is computed. The default value is 10. Usually, it looks better if we set a higher value, e.g. in these examples here we used 70 so that we won't have to scroll too close to the heading but only nearby.

Methods

We can pass the following parameters to the scrollspy() method.

  • "refresh" - If we were using scrollspy and we inserted new contents to the page or removed some, we'd have to refresh the scrollspy by passing this parameter to the scrollspy("refresh") method. The code for refreshing all scrollspies on the page would look like this:
$('[data-spy="scroll"]').each(function () {
    var $spy = $(this).scrollspy("refresh");
})
  • "dispose" - Removes the scrollspy of an element.

Events

We can handle the activate.bs.scrollspy event which is called when the scrollspy activates an item in the navigation. Handling this event could look something like this:

$('[data-spy="scroll"]').on('activate.bs.scrollspy', function () {
    // some reaction...
});

In the next lesson, Bootstrap - Tooltips, we'll finish Bootstrap components :) We'll discuss tooltips.


 

Previous article
Bootstrap - Popovers
All articles in this section
Bootstrap
Skip article
(not recommended)
Bootstrap - Tooltips
Article has been written for you by David Capka Hartinger
Avatar
User rating:
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities