How to implement scrollspy in Bootstrap 4 without relying on nav or list-group components?

Is it possible to implement scrollspy functionality without utilizing the nav or list-group elements?

According to Bootstrap's documentation on scrollspy, it is typically restricted to use within nav or list group components. DOCUMENTATION

How Scrollspy Works

In order for scrollspy to work effectively, certain conditions must be met:

  • If you are compiling our JavaScript from source, util.js is required.
  • It should be applied to a Bootstrap nav component or list group.
  • The element being spied on, usually the <body>, must have position: relative;.
  • When spying on elements other than the <body>, ensure that a height is set and overflow-y: scroll; is included.
  • Anchors (<a>) are necessary and should point to an element with the corresponding id.

This discussion addresses a similar issue but pertains to Bootstrap 3 (not 4), suggesting the addition of role="tablist". This solution may not work in this context. There are numerous queries on Stack Overflow regarding scrollspy, especially concerning Bootstrap 3.

CODE:

/*DEMO*/
nav{top:50%;left:1.5rem;transform:translateY(-50%)}
nav a{display:block;width:20px;height:20px;margin-bottom:.5rem}

/*COLORS*/
nav a{background:black}
nav a.active{background:red}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

</head>
<body data-spy="scroll" data-target="#nav" data-offset="0">

<section class="container-fluid">
    <div class="row">
        <div id="item-1" class="col-12 vh-100 bg-primary"></div>
        <div id="item-2" class="col-12 vh-100 bg-warning"></div>
        <div id="item-3" class="col-12 vh-100 bg-danger"></div>
        <div id="item-4" class="col-12 vh-100 bg-success"></div>
        <div id="item-5" class="col-12 vh-100 bg-info"></div>
    </div>
</section>

<nav id="nav" class="d-flex flex-column position-fixed">
    <a href="#item-1"></a>
    <a href="#item-2"></a>
    <a href="#item-3"></a>
    <a href="#item-4"></a>
    <a href="#item-5"></a>
</nav>


<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>

</body>
</html>

Answer №1

To overcome this issue, simply utilize the required class list-group-item and customize the CSS to your liking:

/*DEMO*/

nav {
  top: 50%;
  left: 1.5rem;
  transform: translateY(-50%)
}

#nav a {
  display: block;
  width: 20px;
  height: 20px;
  margin-bottom: .5rem;
  padding: 0;
  border: none;
  border-radius: 0;
}


/*COLORS*/

#nav a {
  background: black
}

#nav a.active {
  background: red
}
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

</head>

<body data-spy="scroll" data-target="#nav" data-offset="0">

  <section class="container-fluid">
    <div class="row">
      <div id="item-1" class="col-12 vh-100 bg-primary"></div>
      <div id="item-2" class="col-12 vh-100 bg-warning"></div>
      <div id="item-3" class="col-12 vh-100 bg-danger"></div>
      <div id="item-4" class="col-12 vh-100 bg-success"></div>
      <div id="item-5" class="col-12 vh-100 bg-info"></div>
    </div>
  </section>

  <nav id="nav" class="d-flex flex-column position-fixed">
    <a href="#item-1" class="list-group-item"></a>
    <a href="#item-2" class="list-group-item"></a>
    <a href="#item-3" class="list-group-item"></a>
    <a href="#item-4" class="list-group-item"></a>
    <a href="#item-5" class="list-group-item"></a>
  </nav>


  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>

</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Looking for a solution to the ESLint error related to 'no-unused-var' and Google Maps integration. How can I effectively resolve

I'm struggling with what seems to be a simple problem I tried adding /* export myMap */ or /* global myMap */ at the beginning of the script but I keep getting errors Code HTML <h1>My First Google Map</h1> <div id="googleMap" ...

Display completed survey

I am in the process of developing a mobile app that allows users to answer questions in a questionnaire. Once the questionnaire is completed, the user can save it in LocalStorage. Upon revisiting the page, the user will see all previously answered question ...

What is the process for turning off bootstrap form validation?

I am facing an issue with utilizing the default input email validation in my development project. It seems that Bootstrap, which is being used for the website, has its own validation mechanism. Whenever I begin typing in a Bootstrap input field, an error m ...

Introducing a fresh input field that includes a dropdown selection feature

When a user clicks on the "+" button, a new row should be added with a dropdown and input field. I want the input field name to be the dropdown value for each row. If "Facebook" is selected in the first dropdown, it should not appear in the second dropdo ...

Can you suggest some unconventional HTML/CSS attributes and tools for arranging a form in a way that results in a unique tab order?

As part of my role, I am tasked with transforming mock specs provided by our clients into custom web forms. Our application comes equipped with tools specifically developed to streamline this process. Recently, I was presented with a particularly intriguin ...

Identifying a Resizable Div that Preserves its Aspect Ratio During Resizing

Below is the HTML code snippet I'm working with: <div id="myid_templates_editor_text_1" class="myid_templates_editor_element myid_templates_editor_text ui-resizable ui-draggable" style="width: 126.79999999999998px; height: 110px; position: absolut ...

Ensure that selected options are unique across multiple selections

Could you help me with a question that involves matching pairs of words in both Russian and English? <div class="form-group" id="question4"> <label for="q4FirstSelectEN">4</label> <div class="row"> <div class="col-lg ...

Tips for handling transparent areas during a hover event

Is there a way to make only the rhombus image respond to hover events? I want to exclude the transparent area, as shown in this picture. <img src='http://s30.postimg.org/xpd6gwla9/1_Copy.jpg' id="first"> #first:hover { -moz-box-shadow ...

Enhancing larger elements with a combination of CSS background-image gradients and border lines

My design calls for a background image with a line at the end. The line should start right where the background size ends, and in my concept it is grey. It's important that this line remains as one cohesive element. background-image: linear-gradient( ...

Open the iframe link in the main window

As a newcomer to this platform, I am trying to figure out how to make a link open in the parent page when clicking a button within an iframe. Currently, my code opens the link in a new window. <html> <body> <form> <div class ...

Pick the item when the checkbox is selected

I am currently attempting to toggle the visibility of a select element based on whether a checkbox is checked or not, but it doesn't seem to be working as expected. My desired functionality is for the select element to be hidden upon page load and th ...

Vanishing border around the sticky table header

While working on creating a table in an excel style using html and css with a sticky header, I noticed that the borders on the table head appeared strange. Take a look at the code snippet below: table { border-collapse: collapse; position: relative ...

ExpressJS encountered an error due to an unsupported MIME type ('text/html') being used as a stylesheet MIME type

Whenever I start my NodeJS server and enter localhost:8080, I encounter the mentioned error while the page is loading. The head section of my index.html file is provided below. It's puzzling to me why this error is happening, considering that my index ...

Angular: Maximizing Input and Output

I'm having trouble with the function displaying within the input field. My goal is to simply allow the user to enter a name and have it displayed back to them. HTML: <div ng-app = "mainApp" ng-controller = "studentController"> <tr> < ...

I am looking to create a layout with two images placed next to each other using bootstrap, regardless of their dimensions. However, the images do not automatically adjust themselves within

<div class="container" style="background-color: aqua;"> <div class="row"> <div class="col-md-6"> <img src="nature.jpeg" class="img-responsive"> </div> <div class="col-md-6"> ...

Generating DOM elements at specific intervals using Jquery

I am looking to dynamically create 1 div container every x seconds, and repeat this process n times. To achieve this, I have started with the following code: $(document).ready(function() { for (var i = 0; i < 5; i++) { createEle(i); } }); f ...

The output is: [object of type HTMLSpanElement]

<form> <table> <tr> <td>Distance:</td> <td><input type="number" id="distance" onKeyUp="calculate();">m</td> </tr> <tr> <td>Time:</td> ...

Pressing a button meant to transfer text from a textarea results in the typed content failing to show up

Having trouble with a custom text area called a math field. I'm currently interning on a project to build a math search engine, where users can input plain text and LaTeX equations into a query bar. The issue I'm facing is that sometimes when th ...

Trouble arises when adding HTML elements to a Content Editable Div. Any text inputted after programmatically inserting HTML content will merge with the last HTML tag instead

https://i.sstatic.net/bKIVm.pngI am currently working on a project that involves creating message templates within an app. Users have the ability to add placeholders for fields like names to these templates by clicking a button. They can also remove these ...

Ways to modify the jquery script to display on page load rather than on scrolling action

Currently in the process of working on my site, www.runebs.dk. Utilizing a script to activate information for each project. JS.. $('.showHide').on('click',function(){ $(this).toggleClass('active'); $( '#subHead ...