Bootstrap- Scrollspy Plugin

Introduction

The Scrollspy (auto-updating nav) plugin allows you to target specific page portions based on where you are on the page. In the simple implementation, you can add .active classes to the navbar based on the scroll position.

To identify which link is now active in the viewport, automatically change Bootstrap navigation or list group components based on scroll position.

Scrollspy.js is required if you wish to use this plugin's capabilities individually. If not, you can use bootstrap.js or bootstrap.min.js, as described in the chapter Bootstrap Plugins Overview.

How to use the Scrollspy Plugin?

Scrollspy behaviour can be added to your topbar navigation:

Using data-attributes

On the element, you want to spy on, add data-spy = "scroll" (typically the body). Then, for every Bootstrap .nav component, add the attribute data-target with the ID or class of the parent element. You'll need components in the body of the page with matching IDs to the links you're spying on for this to work.

<body data-spy = "scroll" data-target = ".navbar-example">
   ...
   <div class = "navbar-example">
      <ul class = "nav nav-tabs">
         ...
      </ul>
   </div>
   ...
</body>

Using Javascript

You can use JavaScript instead of data attributes to activate the scrollspy by selecting the element to spy on and then running the. The function scrollspy() allows you to scroll through a list of items.

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

Example in navbar

The use of the scrollspy plugin via data attributes is demonstrated in the following example.

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Scrollspy</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>

<body>
    <nav id="navbar-example" class="navbar navbar-default navbar-static" role="navigation">
        <div class="navbar-header">
            <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".bs-js-navbar-scrollspy">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">New Tutorial</a>
        </div>
        <div class="collapse navbar-collapse bs-js-navbar-scrollspy">
            <ul class="nav navbar-nav">
                <li><a href="#orange">Orange</a></li>
                <li><a href="#mango">Mango</a></li>
                <li class="dropdown">
                    <a href="#" id="navbarDrop1" class="dropdown-toggle" data-toggle="dropdown">Vegetables
                        <b class="caret"></b>
                    </a>
                    <ul class="dropdown-menu" role="menu" aria-labelledby="navbarDrop1">
                        <li><a href="#tomato" tabindex="-1">Tomato</a></li>
                        <li><a href="#potato" tabindex="-1">Potato</a></li>
                        <li class="divider"></li>
                        <li><a href="#beans" tabindex="-1">Beans</a></li>
                    </ul>
                </li>
            </ul>
        </div>
    </nav>
    <div data-spy="scroll" data-target="#navbar-example" data-offset="0"
        style="height:200px;overflow:auto; position: relative;">
        <h4 id="orange">Orange</h4>
        <p>The orange is the fruit of several citrus species in the Rutaceae family; it is most commonly associated with Citrus sinensis, also known as sweet orange, to distinguish it from the related Citrus aurantium, popularly known as bitter orange.
        </p>
        <h4 id="mango">Mango</h4>
        <p>A mango is a tropical stone fruit produced by the Mangifera indica tree. It originated in northern Myanmar, Bangladesh, and northeastern India, according to legend.</p>
        <h4 id="tomato">Tomato</h4>
        <p>The edible berries of the Solanum lycopersicum plant, often known as the tomato plant, are tomatoes. The species originated in Western South America and Central America. Tomate comes from the Nahuatl word tomatl, which is also the source of the English term tomato.
        </p>
        <h4 id="potato">Potato</h4>
        <p>The potato is a root vegetable native to the Americas that is made up of a starchy tuber from the plant Solanum tuberosum. The plant is a perennial nightshade from the Solanaceae family. From Canada to southern Chile, wild potato species can be found all over the Americas.
        </p>
        <h4 id="beans">Beans</h4>
        <p>Beans are the seeds of numerous genera of flowering plants in the Fabaceae family that are used as vegetables for human and animal use. 
        </p>
        <p>They may be prepared in a variety of ways, including boiling, frying, and baking, and are used in many traditional cuisines around the world.
        </p>
    </div>
</body>

</html>


Output

Options

Data attributes or JavaScript can be used to pass options. Append the option name to data- for data attributes, as in data-offset="”. The possibilities are listed in the table below.

Name

Type

Default

Description

offsetnumber10When computing the position of the scroll, pixels offset from the top.

 

Methods

scrollspy(‘refresh’)

 If you're using scrollspy to add or remove elements from the DOM, you'll need to call the refresh method as follows:

$('[data-spy="scroll"]').each(function () {
  var $spy = $(this).scrollspy('refresh')
})

scrollspy(‘dispose’)

The scrollspy of an element is destroyed.

Example using Methods

The .scrollspy('refresh') method is demonstrated in the following example.

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Scrollspy</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>

<body>
    <nav id="myScrollspy" class="navbar navbar-default navbar-static" role="navigation">
        <div class="navbar-header">
            <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".bs-js-navbar-scrollspy">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">New Tutorial </a>
        </div>
        <div class="collapse navbar-collapse bs-js-navbar-scrollspy">
            <ul class="nav navbar-nav">
                <li class="active"><a href="#orange">Orange</a></li>
                <li><a href="#mango">Mango</a></li>
                <li class="dropdown">
                    <a href="#" id="navbarDrop1" class="dropdown-toggle" data-toggle="dropdown">Vegetables
                        <b class="caret"></b>
                    </a>
                    <ul class="dropdown-menu" role="menu" aria-labelledby="navbarDrop1">
                        <li><a href="#tomato" tabindex="-1">Tomato</a></li>
                        <li><a href="#potato" tabindex="-1">Potato</a></li>
                        <li class="divider"></li>
                        <li><a href="#beans" tabindex="-1">Beans</a></li>
                    </ul>
                </li>
            </ul>
        </div>
    </nav>
    <div data-spy="scroll" data-target="#myScrollspy" data-offset="0"
        style="height:200px;overflow:auto; position: relative;">
        <div class="section">
            <h4 id="orange">Orange<small><a href="#" onclick="removeSection(this);">
                        &times; Remove this section</a></small>
            </h4>
            <p>The orange is the fruit of several citrus species in the Rutaceae family; it is most commonly associated with Citrus sinensis, also known as sweet orange, to distinguish it from the related Citrus aurantium, popularly known as bitter orange.
            </p>
        </div>
        <div class="section">
            <h4 id="mango">Mango<small></small></h4>
            <p>A mango is a tropical stone fruit produced by the Mangifera indica tree. It originated in northern Myanmar, Bangladesh, and northeastern India, according to legend.</p>
        </div>
        <div class="section">
            <h4 id="tomato">Tomato<small><a href="#" onclick="removeSection(this);">
                        &times; Remove this section</a></small>
            </h4>
            <p>The edible berries of the Solanum lycopersicum plant, often known as the tomato plant, are tomatoes. The species originated in Western South America and Central America. Tomate comes from the Nahuatl word tomatl, which is also the source of the English term tomato.

            </p>
        </div>
        <div class="section">
            <h4 id="potato">Potato</h4>
            <p>The potato is a root vegetable native to the Americas that is made up of a starchy tuber from the plant Solanum tuberosum. The plant is a perennial nightshade from the Solanaceae family. From Canada to southern Chile, wild potato species can be found all over the Americas.

            </p>
        </div>
        <div class="section">
            <h4 id="beans">Beans</h4>
            <p>Beans are the seeds of numerous genera of flowering plants in the Fabaceae family that are used as vegetables for human and animal use. 
        </p>
        <p>They may be prepared in a variety of ways, including boiling, frying, and baking, and are used in many traditional cuisines around the world.
        </p>

        </div>
    </div>
    <script type="text/javascript">
        $(function () {
            removeSection = function (e) {
                $(e).parents(".section").remove();
                $('[data-spy="scroll"]').each(function () {
                    var $spy = $(this).scrollspy('refresh')
                });
            }
            $("#myScrollspy").scrollspy();
        });
    </script>
</body>

</html>


Output

Events

The events to work with scrollspy are shown in the table below. To hook into the function, utilise this event.

Event Type

Description

activate.bs.scrollspyWhen the scrollspy activates a new item, this event triggers on the scroll element.

 

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

Example of Event

This example shows the use of activate.bs.scrollspy event:

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Scrollspy</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <script>
        $(document).ready(function () {
            removeSection = function (e) {
                $(e).parents(".fruit").remove();

                $('[data-spy="scroll"]').each(function () {
                    var $spy = $(this).scrollspy('refresh')
                });
            }

            $("#Navexample").scrollspy();

            // When a scrollspy item is activated, the event is triggered.
            $("#Navexample").on('activate.bs.scrollspy', function () {
                var currentSection = $(".nav li.active > a").text();
                $("#spyevent").html("Current Item being viewed >> " + currentSection);
            })

        });
    </script>

    <style>
        .scroll-box {
            height: 250px;
            position: relative;
            overflow: auto;
            font-size: 2em;
        }
    </style>
</head>

<body>
    <div class="container">
        <nav id="Navexample" class="navbar navbar-default" role="navigation">

            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbarCollapse">

                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>

                <a class="navbar-brand" href="#">New Tutorial</a>
            </div>

            <div class="collapse navbar-collapse" id="navbarCollapse">
                <ul class="nav navbar-nav">
                    <li class="active"><a href="#orange">Orange</a></li>
                    <li><a href="#mango">Mango</a></li>

                    <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Vegetables<b
                                class="caret"></b></a>

                        <ul class="dropdown-menu">
                            <li><a href="#tomato">Tomato</a></li>
                            <li><a href="#potato">Potato</a></li>
                            <li><a href="#beans">Beans</a></li>
                        </ul>

                    </li>

                    <li><a href="#banana">Banana</a></li>
                </ul>
            </div>

        </nav>

        <div class="scroll-box" data-spy="scroll" data-offset="0">
            <div class="fruit">

                <h3 id="orange">Orange
                    <small><a href="#" onclick="removeFruit(this);">Remove Fruit ×</a></small>
                </h3>

                <p>The orange is the fruit of several citrus species in the Rutaceae family; it is most commonly
                    associated with Citrus sinensis, also known as sweet orange, to distinguish it from the related
                    Citrus aurantium, popularly known as bitter orange.</p>
            </div>

            <hr>

            <div class="fruit">
                <h3 id="mango">Mango
                    <small><a href="#" onclick="removeFruit(this);">Remove Fruit ×</a></small>
                </h3>

                <p>A mango is a tropical stone fruit produced by the Mangifera indica tree. It originated in northern Myanmar, Bangladesh, and northeastern India, according to legend.</p>
            </div>

            <hr>

            <div class="fruit">
                <h3 id="vegetable">Vegetable
                    <small><a href="#" onclick="removeFruit(this);"> Remove this ×</a></small>
                </h3>

                <p>Vegetables are plant portions that are utilised as food by humans and other animals. The original
                    definition is still widely used, and it refers to all edible plant stuff, including flowers, fruits,
                    stems, leaves, roots, and seeds, when applied to plants collectively. A different definition of the
                    phrase is sometimes adopted haphazardly, influenced by culinary and cultural traditions. It may
                    exclude fruits, flowers, nuts, and cereal grains derived from some plants, although it includes
                    savoury fruits like tomatoes and courgettes, flowers like broccoli, and seeds like pulses.</p>
            </div>

            <hr>

            <div class="fruit">
                <h4 id="tomato">Tomato
                    <small><a href="#" onclick="removeFruit(this);"> Remove this ×</a></small>
                </h4>

                <p>The edible berries of the Solanum lycopersicum plant, often known as the tomato plant, are tomatoes. The species originated in Western South America and Central America. Tomate comes from the Nahuatl word tomatl, which is also the source of the English term tomato.</p>
            </div>

            <div class="fruit">
                <h4 id="potato">Potato
                    <small><a href="#" onclick="removeFruit(this);"> Remove this ×</a></small>
                </h4>

                <p>The potato is a root vegetable native to the Americas that is made up of a starchy tuber from the plant Solanum tuberosum. The plant is a perennial nightshade from the Solanaceae family. From Canada to southern Chile, wild potato species can be found all over the Americas.</p>
            </div>

            <div class="fruit">
                <h4 id="beans">Beans
                    <small><a href="#" onclick="removeFruit(this);">Remove this ×</a></small>
                </h4>

                <p>Beans are the seeds of numerous genera of flowering plants in the Fabaceae family that are used as
                    vegetables for human and animal use. They may be prepared in a variety of ways, including boiling, frying, and baking, and are used in many traditional cuisines around the world. </p>
            </div>

            <hr>

            <div class="fruit">
                <h3 id="banana">Banana
                    <small><a href="#" onclick="removeFruit(this);">Remove Fruit ×</a></small>
                </h3>

                <p>Bananas are elongated, edible berries produced by several species of big herbaceous flowering plants
                    of the genus Musa. Cooking bananas are sometimes referred to as "plantains" in some countries, to
                    distinguish them from dessert bananas.</p>
            </div>

        </div>
        <hr>

        <h4 id="spyevent" class="text-info"></h4>
    </div>
</body>

</html>


Output

Frequently Asked Questions

  1. In Bootstrap, what is a Scrollspy?
    We've been to many websites where the navigation bars refresh themselves as the user travels down the page. Scrollspy operates following the user's current viewing position or scroll position. When scrolling the area, Bootstrap scrollspy automatically targets the navigation bar contents.
     
  2. What are the attribute values in Scrollspy?
    data-spy: It is used to monitor the user's current scrolling position.
    data-target: This attribute connects the navigation bar to the scrollable area.
    data-offset: When calculating the part of the scroll, this attribute provides the number of pixels to offset from the top.

Key takeaways

In this article, we have discussed the scrollspy plugin. The Bootstrap scrollspy is a navigation mechanism that highlights navigation links based on the scroll position to show the visitor where they are on the website.

If you're utilising bookmark links to send users to different portions of a website with a lot of material, the scrollspy will make your web page more elegant and accessible.

If you want to get started with bootstrap for free and want to learn more about it then you can visit Learn Bootstrap and check out our blog to know why bootstrap is cool and how it helps you in designing your website with Responsive Network Vanilla utilising HTML, CSS & Bootstrap.

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think