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 haveposition: relative;
.- When spying on elements other than the
<body>
, ensure that aheight
is set andoverflow-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>