Open In App

Bootstrap 5 Scrollspy Events

Last Updated : 09 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Bootstrap 5 Scrollspy Event is fired on the scroll element whenever a new item becomes activated by the scrollspy feature in Bootstrap, indicating a change in visibility within the viewport.

Bootstrap 5 Scrollspy Events

  • activate.bs.scrollspy: This event is triggered when a new item is activated by the scrollspy. When a link is clicked, it displays the event name associated with the activation.

Syntax:

document.addEventListener('activate.bs.scrollspy', function(event){
    // Javascript code here
});

Example 1: In this example, the scrollspy feature updates the navigation based on scroll position and triggers the ‘activate.bs.scrollspy’ event. When activated, the corresponding link’s text color changes to white.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <title>Bootstrap 5 Scrollspy Events </title>
    <link href=
          rel="stylesheet"
          integrity=
"sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM"
          crossorigin="anonymous">
      <script src=
            integrity=
"sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" 
            crossorigin="anonymous">
    </script>
  
</head>
  
<body>
    <h1 class="text-success">
          GeeksForGeeks
      </h1>
    <nav class="navbar bg-secondary 
                px-3 mb-3 w-75" 
         data-bs-spy="scroll" 
         data-bs-target="#myScrollspy">
        <ul class="navbar-nav" 
            id="myScrollspy">
            <li class="nav-item">
                <a class="nav-link active"
                   href="#section1">
                    HTML
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" 
                   href="#section2">
                    CSS
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" 
                   href="#section3">
                    Bootstrap
                </a>
            </li>
        </ul>
    </nav>
    <div data-bs-spy="scroll" 
         data-bs-target="#myScrollspy" 
         data-bs-root-margin="0px 0px -40%"
         data-bs-smooth-scroll="true" 
         class="scrollspy-example 
                bg-body-tertiary 
                p-3 rounded-2" 
         tabindex="0">
        <section id="section1">
            <h2>HTML Introduction</h2>
            <p>
                <img class="h-50 w-50"
                     src=
                     alt="HTML">
            </p>
        </section>
        <br><br>
        <section id="section2">
            <h2>CSS Introduction</h2>
            <p>
                <img class="h-50 w-50" 
                     src=
                     alt="CSS">
            </p>
        </section>
        <br><br>
        <section id="section3">
            <h2>Bootstrap Introduction</h2>
            <p>
                <img class="h-50 w-50"
                     src=
                     alt="Bootstrap">
            </p>
        </section>
    </div>
  
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            let scrollSpy =
                new bootstrap.ScrollSpy(document.body, {
                    target: '#myScrollspy'
                });
  
       document.addEventListener('activate.bs.scrollspy', function (event) {
                let activatedItem = event.relatedTarget;
                activatedItem.style.color = 'white';
            });
        });
    </script>
</body>
  
</html>


Output:

scroll-update-2

Example 2: In this example, we have Scrollspy Events. It includes a navigation bar that highlights the active link based on the section currently in the viewport.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <link rel="stylesheet" href=
    <script src=
    </script>
    <title>
          Bootstrap 5 Scrollspy Events 
      </title>
    <style>
        .section {
            height: 400px;
            margin-bottom: 50px;
        }
  
        .nav-link.active {
            font-weight: bold;
        }
    </style>
</head>
  
<body data-bs-spy="scroll" 
      data-bs-target="#scrollspy" 
      data-bs-offset="50">
  
    <div id="scrollspy">
        <ul class="nav nav-pills">
            <li class="nav-item">
                <a class="nav-link" 
                   href="#section1">
                    HTML
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" 
                   href="#section2">
                    CSS
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" 
                   href="#section3">
                    Bootstrap
                </a>
            </li>
        </ul>
    </div>
  
    <div id="section1" 
         class="section">
        <h2>HTML</h2>
        <p>
            HTML (Hypertext Markup Language) is
            the standard markup language used
            for creating the structure and
            content of web pages. It consists of
            a set of tags and elements that define
            the various components of a webpage,
            such as headings, paragraphs, images,
            links, forms,and more.
            HTML provides a semantic structure to
            organize content and facilitates the
            presentation and interaction of web
            pages in browsers. It serves as the
            backbone of web development, allowing
            developers to create the skeleton of a
            webpage and define its content hierarchy.
        </p>
    </div>
  
    <div id="section2" 
         class="section">
        <h2>CSS</h2>
        <p>
            CSS (Cascading Style Sheets) is a style
            sheet language used to describe the
            presentation and visual appearance of
            HTML elements on a web page.It provides
            a set of rules that define how HTML
            elements should be displayed, including
            aspects like layout, color, font styles,
            spacing,and more. CSS enables developers
            to separate the design and layout from the
            structure of the HTML document, making it
            easier to apply consistent styles across
            multiple web pages. With CSS, you can
            create responsive and visually appealing
            designs, customize the look and feel of
            elements, and enhance the overall user
            experience.
        </p>
    </div>
  
    <div id="section3" 
         class="section">
        <h2>Bootstrap</h2>
        <p>
            Bootstrap is a popular front-end framework
            that provides a collection of pre-designed
            CSS and JavaScript components, templates,
            and utilities.It offers a responsive grid
            system, CSS styles, and ready-to-use UI
            components, such as navigation bars, buttons,
            forms, modals, and more.Bootstrap simplifies
            and accelerates web development by providing
            a robust foundation for creating responsive
            and mobile-friendly websites and web
            applications.It promotes consistency and
            responsiveness across different devices and
            browsers, allowing developers to quickly
            build professional-looking and feature-rich
            interfaces without starting from scratch.
            Bootstrap's grid system and styling classes
            streamline the layout and appearance of web
            content, while its JavaScript components
            enhance interactivity and user experience.
        </p>
    </div>
  
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            let navLinks =
                document.querySelectorAll('#scrollspy a.nav-link');
            let sections =
                document.querySelectorAll('.section');
  
            navLinks.forEach(function (navLink) {
                navLink.addEventListener('click', function (event) {
                    event.preventDefault();
                    let targetSection =
                        document.querySelector(navLink.getAttribute('href'));
                    targetSection.scrollIntoView({ behavior: 'smooth' });
                });
            });
  
            sections.forEach(function (section) {
                section.addEventListener('activate.bs.scrollspy',
                    function () {
                        let sectionId =
                            section.getAttribute('id');
                        navLinks.forEach(function (navLink) {
                            navLink.classList.toggle('active',
                                navLink.getAttribute('href') === '#' + sectionId);
                        });
                        console.log('Section activated:', sectionId);
                    });
  
                section.addEventListener('deactivate.bs.scrollspy',
                    function () {
                        let sectionId = section.getAttribute('id');
                        navLinks.forEach(function (navLink) {
                            navLink.classList.remove('active');
                        });
                        console.log('Section deactivated:', sectionId);
                    });
            });
        });
    </script>
</body>
  
</html>


Output:

scrollspy-2.gif

Reference: https://getbootstrap.com/docs/5.0/components/scrollspy/#events



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads