Please note, this is a STATIC archive of website www.tutorialrepublic.com from 10 Sep 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
BOOTSTRAP BASIC
BOOTSTRAP ADVANCED
BOOTSTRAP EXAMPLES
BOOTSTRAP ARCHIVE
Advertisements

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:

<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>

Creating ScrollSpy via Data Attributes

You can easily add scrollspy behavior to your navbar via data attributes without writing a single line of JavaScript code. Let's try out the following example to see how it works:

<body data-bs-spy="scroll" data-bs-offset="60" data-bs-target="#myNavbar">
    <nav id="myNavbar" class="navbar navbar-light bg-light fixed-top">
        <div class="container-fluid">
            <a href="#" class="navbar-brand">Navbar</a>
            <ul class="nav nav-pills">
                <li class="nav-item">
                    <a href="#section1" class="nav-link">Section 1</a>
                </li>
                <li class="nav-item">
                    <a href="#section2" class="nav-link">Section 2</a>
                </li>
                <li class="nav-item">
                    <a href="#section3" class="nav-link">Section 3</a>
                </li>
                <li class="nav-item dropdown">
                    <a href="#" class="nav-link dropdown-toggle" data-bs-toggle="dropdown">Section 4</a>
                    <div class="dropdown-menu">
                        <a href="#section4dot1" class="dropdown-item">Section 4.1</a>
                        <a href="#section4dot2" class="dropdown-item">Section 4.2</a>
                        <a href="#section4dot3" class="dropdown-item">Section 4.3</a>
                    </div>
                </li>
                <li>
                    <a href="#section5" class="nav-link">Section 5</a>
                </li>
            </ul>
        </div>
    </nav>
    <div class="container">
        <div id="section1">
            <h2>Section 1</h2>
            <p>This is section 1 content...</p>
        </div>
        <hr>
        <div id="section2">
            <h2>Section 2</h2>
            <p>This is section 2 content...</p>
        </div>
        <hr>
        <div id="section3">
            <h2>Section 3</h2>
            <p>This is section 3 content...</p>
        </div>
        <hr>
        <h2>Section 4</h2>
        <p>This is section 4 content</p>
        <div id="section4dot1">
            <h3>Section 4.1</h3>
            <p>This is section 4.1 content...</p>
        </div>
        <div id="section4dot2">
            <h3>Section 4.2</h3>
            <p>This is section 4.2 content...</p>
        </div>
        <div id="section4dot3">
            <h3>Section 4.3</h3>
            <p>This is section 4.3 content...</p>
        </div>
        <hr>
        <div id="section5">
            <h2>Section 5</h2>
            <p>This is section 5 content...</p>
        </div>
    </div>
</body>

You might be wondering what this code was all about. Well, let's go through each part of this scrollspy example code one by one for a better understanding.

Explanation of Code

The Bootstrap scrollspy has basically two components — the target (e.g. nav or list group) and the scrollable area to spy on, which is often the <body> section.

  • The data-bs-spy="scroll" attribute (line no-01) is applied to the element you want to spy on, which is simply the <body> element in our case.
  • The data-bs-target attribute is added to the element we're spying on (i.e. the <body> element) with the ID or class of the parent element of any Bootstrap .nav component, so that nav links can be targeted by the scrollspy for highlighting purpose.
  • The optional data-bs-offset attribute specifies the number of pixels to offset from top when calculating the position of scroll. Adjust the offset value if the targeted links are highlighting too early or too late. The default value is 10 pixels.

Rest of the thing is self explanatory, such as the .navbar element specifies a Bootstrap navbar, whereas the element <a href="#section1">Section 1</a> (line no-7) creates a bookmark link, the .dropdown element (line no-15) creates a dropdown menu, and so on.


Creating ScrollSpy via JavaScript

You may also add scrollspy manually using the JavaScript — just call the scrollspy() Bootstrap method with the id or class selector of the navbar in your JavaScript code.

Example

jQuery JavaScript
Try this code »
<script>
$(document).ready(function(){
    $("body").scrollspy({
        target: "#myNavbar"
    }) 
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function(){
    var myScrollSpy = new bootstrap.ScrollSpy(document.body, {
        target: "#myNavbar"
    })
});
</script>

Options

There are certain options which may be passed to scrollspy() Bootstrap method to customize the functionality of a scrollspy. Options can be passed via data attributes or JavaScript.

For setting the scrollspy options via data attributes, just append the option name to data-bs-, like data-bs-offset="0", data-bs-method="position", and so on.

Name Type Default Value Description
offset number 10 Number of pixels to offset from top when calculating position of scroll.
method string auto

Finds which section the spied element is in. The value auto will choose the best method get scroll coordinates.

Whereas, the value offset will use jQuery offset method to get scroll coordinates, and the value position will use jQuery position method to get scroll coordinates.

target string |
jQuery object |
DOM element
Specifies element to apply Scrollspy plugin.

Methods

These are the standard bootstrap's scrollspy methods:

Passing options

You can additionally pass options to the scrollspy using options object.

The following example will set offset from top when calculating scroll position.

Example

jQuery JavaScript
Try this code »
<script>
$(document).ready(function(){
    $("body").scrollspy({
        offset: 70
    }) 
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function(){
    var myScrollSpy = new bootstrap.ScrollSpy(document.body, {
        offset: 70
    })
});
</script>

refresh

You'll need to call this method when you're using scrollspy in conjunction with adding or removing elements from the DOM. Let's try out an example and see how it really works:

Example

jQuery JavaScript
Try this code »
<script>
$(document).ready(function(){
    $('[data-spy="scroll"]').each(function(){
        $(this).scrollspy("refresh");
    }); 
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function(){
    var scrollspyList = [].slice.call(document.querySelectorAll('[data-bs-spy="scroll"]'));
    scrollspyList.forEach(function(element){
        bootstrap.ScrollSpy.getInstance(element).refresh();
    })
});
</script>

dispose

This method destroys an element's scrollspy (i.e. removes stored data on the DOM element).

Example

jQuery JavaScript
Try this code »
<script>
$(document).ready(function(){
    $("#myBtn").click(function(){
        var myScrollspy = bootstrap.ScrollSpy.getInstance($("#myContent")[0]);
        console.log(myScrollspy);
        // {_element: div#myContent, _scrollElement: div#myContent, _config: {…}, _selector: "#myNavbar .nav-link, #myNavbar .list-group-item, #myNavbar .dropdown-item", _offsets: Array(5), …}

        $("#myContent").scrollspy("dispose");
        console.log(myScrollspy);
        // {_element: null, _scrollElement: null, _config: null, _selector: null, _offsets: null, …}
    });
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function() {
    var btn = document.getElementById("myBtn");
    var element = document.getElementById("myContent");

    btn.addEventListener("click", function(){
        var myScrollspy = bootstrap.ScrollSpy.getInstance(element);
        console.log(myScrollspy);
        // {_element: div#myContent, _scrollElement: div#myContent, _config: {…}, _selector: "#myNavbar .nav-link, #myNavbar .list-group-item, #myNavbar .dropdown-item", _offsets: Array(5), …}
        
        myScrollspy.dispose();
        console.log(myScrollspy);
        // {_element: null, _scrollElement: null, _config: null, _selector: null, _offsets: null, …}
    });
});
</script>

getInstance

This is a static method which allows you to get the scrollspy instance associated with a DOM element.

Example

jQuery JavaScript
Try this code »
<script>
$(document).ready(function(){
    $("#myBtn").click(function(){
        var myScrollspy = bootstrap.ScrollSpy.getInstance($("#myContent")[0]);
        console.log(myScrollspy);
        // {_element: div#myContent, _scrollElement: div#myContent, _config: {…}, _selector: "#myNavbar .nav-link, #myNavbar .list-group-item, #myNavbar .dropdown-item", _offsets: Array(5), …}
    });
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function() {
    var btn = document.getElementById("myBtn");
    var element = document.getElementById("myContent");

    btn.addEventListener("click", function(){
        var myScrollspy = bootstrap.ScrollSpy.getInstance(element);
        console.log(myScrollspy);
        // {_element: div#myContent, _scrollElement: div#myContent, _config: {…}, _selector: "#myNavbar .nav-link, #myNavbar .list-group-item, #myNavbar .dropdown-item", _offsets: Array(5), …}
    });
});
</script>

getOrCreateInstance

This is a static method which allows you to get the scrollspy instance associated with a DOM element, or create a new one in case if the scrollspy wasn't initialized.

Example

jQuery JavaScript
Try this code »
<script>
$(document).ready(function(){
    $("#myBtn").click(function(){
        var myScrollspy = bootstrap.ScrollSpy.getOrCreateInstance($("#myContent")[0]);
        console.log(myScrollspy);
        // {_element: div#myContent, _scrollElement: div#myContent, _config: {…}, _selector: "#myNavbar .nav-link, #myNavbar .list-group-item, #myNavbar .dropdown-item", _offsets: Array(5), …}
    });
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function() {
    var btn = document.getElementById("myBtn");
    var element = document.getElementById("myContent");

    btn.addEventListener("click", function(){
        var myScrollspy = bootstrap.ScrollSpy.getOrCreateInstance(element);
        console.log(myScrollspy);
        // {_element: div#myContent, _scrollElement: div#myContent, _config: {…}, _selector: "#myNavbar .nav-link, #myNavbar .list-group-item, #myNavbar .dropdown-item", _offsets: Array(5), …}
    });
});
</script>

Events

Bootstrap's scrollspy class includes few events for hooking into scrollspy functionality.

Event Description
activate.bs.scrollspy This event fires whenever a new item becomes activated by the scrollspy.

The following example displays an alert message when a new item becomes highlighted by the scrollspy. Let's try it out and see how it actually works.

Example

jQuery JavaScript
Try this code »
<script>
$(document).ready(function(){
    $("#myNavbar").on("activate.bs.scrollspy", function(){
        var currentItem = $(".nav li.active > a").text();
        $("#info").empty().html("Currently you are viewing - " + currentItem);
    })
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function(){
    var scrollspyList = [].slice.call(document.querySelectorAll('[data-bs-spy="scroll"]'));
    scrollspyList.forEach(function(element){
        bootstrap.ScrollSpy.getInstance(element).refresh();
    })
});
</script>
Advertisements
Bootstrap UI Design Templates