Bootstrap 4 Scrollspy

Welcome to The Coding College! Scrollspy is a Bootstrap 4 feature that automatically updates navigation links to reflect the currently visible section on a page. It’s especially useful for creating dynamic one-page layouts or content-heavy websites.

In this advanced guide, we’ll explore the implementation of Bootstrap 4 Scrollspy with tips and techniques to make it more dynamic and customizable.

What is Scrollspy?

Scrollspy is a feature that monitors scrolling and highlights the navigation links corresponding to the visible sections of a page. It enhances user experience by providing a clear indication of the current location on the page.

Basic Scrollspy Setup

Before diving into advanced techniques, let’s quickly recap the basic Scrollspy implementation.

Requirements:

  1. A navigation bar or list with links pointing to section IDs.
  2. Section elements with corresponding IDs.
  3. data-spy="scroll" and data-target attributes to initialize Scrollspy.

Example: Basic Scrollspy

<!DOCTYPE html>  
<html lang="en">  
<head>  
  <meta charset="UTF-8">  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  <title>Bootstrap 4 Scrollspy</title>  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">  
  <style>  
    section {  
      height: 100vh;  
      padding: 50px;  
    }  
  </style>  
</head>  
<body data-spy="scroll" data-target="#navbar" data-offset="70">  

  <!-- Navigation Bar -->  
  <nav id="navbar" class="navbar navbar-expand-lg navbar-light bg-light fixed-top">  
    <a class="navbar-brand" href="#">Scrollspy</a>  
    <ul class="navbar-nav ml-auto">  
      <li class="nav-item"><a class="nav-link" href="#section1">Section 1</a></li>  
      <li class="nav-item"><a class="nav-link" href="#section2">Section 2</a></li>  
      <li class="nav-item"><a class="nav-link" href="#section3">Section 3</a></li>  
    </ul>  
  </nav>  

  <!-- Sections -->  
  <section id="section1" class="bg-primary text-white">  
    <h1>Section 1</h1>  
  </section>  
  <section id="section2" class="bg-secondary text-white">  
    <h1>Section 2</h1>  
  </section>  
  <section id="section3" class="bg-success text-white">  
    <h1>Section 3</h1>  
  </section>  

  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>  
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>  
</body>  
</html>  

Advanced Scrollspy Features

Now that you’re familiar with the basics, let’s explore some advanced techniques to enhance Scrollspy functionality.

1. Smooth Scrolling

By default, navigation links jump directly to sections. You can add smooth scrolling for a better user experience.

Example: Smooth Scrolling with jQuery

<script>  
  $(document).ready(function() {  
    $('a.nav-link').on('click', function(event) {  
      event.preventDefault();  
      const target = $(this.hash);  
      if (target.length) {  
        $('html, body').animate({  
          scrollTop: target.offset().top - 70  
        }, 800);  
      }  
    });  
  });  
</script>  

Add this script to the previous example to enable smooth scrolling.

2. Dynamic Offsets

The data-offset attribute defines the distance from the top of the viewport to activate a section. If your website has a sticky or fixed header, set the offset dynamically.

Example: Dynamic Offset with JavaScript

$(document).ready(function() {  
  const navbarHeight = $('.navbar').outerHeight();  
  $('body').attr('data-offset', navbarHeight);  
});  

3. Highlight Parent Links

If your navigation menu includes dropdowns, you can highlight the parent link when a child section is active.

Example: Highlight Parent Links

$('body').on('activate.bs.scrollspy', function() {  
  $('.nav-item').removeClass('active');  
  $('.nav-item > .active').parent().addClass('active');  
});  

4. Horizontal Scrollspy

Scrollspy isn’t limited to vertical scrolling. Use it for horizontal scrolling by tweaking CSS and JavaScript.

Example: Horizontal Scrollspy

<div class="scrollspy-horizontal" data-spy="scroll" data-target="#horizontalNav">  
  <div id="section1" style="width: 100vw; display: inline-block;">Section 1</div>  
  <div id="section2" style="width: 100vw; display: inline-block;">Section 2</div>  
  <div id="section3" style="width: 100vw; display: inline-block;">Section 3</div>  
</div>  

<nav id="horizontalNav" class="navbar">  
  <a href="#section1">Section 1</a>  
  <a href="#section2">Section 2</a>  
  <a href="#section3">Section 3</a>  
</nav>  

Use overflow-x: auto on the container to enable horizontal scrolling.

5. Custom Scrollspy Events

Bootstrap Scrollspy triggers events you can listen for to add custom functionality.

Available Events

  • activate.bs.scrollspy: Triggered when a section becomes active.

Example: Logging Active Section

$('body').on('activate.bs.scrollspy', function(event, target) {  
  console.log('Active section:', target);  
});  

6. Multi-Page Scrollspy

Scrollspy isn’t limited to single-page designs. You can use it across multiple pages by synchronizing links with their respective sections.

Troubleshooting Scrollspy

Here are some common issues with Scrollspy and how to resolve them:

  1. Scrollspy Not Working:
    Ensure the data-spy attribute is added to the <body> tag and data-target points to a valid navigation container.
  2. Incorrect Highlighting:
    Adjust the data-offset value to account for fixed headers or margins.
  3. Sections Overlapping:
    Add padding or margins to ensure sections are properly spaced.

Styling Scrollspy

You can style active navigation links using CSS. By default, Bootstrap applies the .active class to the active link.

Example: Custom Active Link Style

.nav-link.active {  
  background-color: #007bff;  
  color: white;  
  border-radius: 5px;  
}  

Conclusion

Bootstrap 4 Scrollspy is a powerful tool for creating dynamic, user-friendly navigation systems. By combining smooth scrolling, dynamic offsets, and custom styling, you can deliver a seamless experience on your website.

Leave a Comment