This might seem a bit hackish, but I think this is the only way to achieve your desired behavior without modifying the scrollspy
javascript itself.
The idea here is to create anchors for the aside elements as well, but make these anchors hidden. As the order of the menu items is not important for the scrollspy
, these “unnecessary” menu items can be grouped and wrapped into a single hidden parent element. Check the snippet below.
#content {
position: relative;
overflow-y: scroll;
height: 100vh;
}
/* Just basic styling */
#content > div {
height: 50vh;
padding: 15px;
}
#content > div:nth-child(2n) {
background-color: lightgrey;
}
#content > div:last-child {
height: 100vh;
}
.aside {
background-color: pink !important;
}
<div class="container-fluid">
<div class="row">
<div class="col-3">
<nav id="navbar-scollspy" class="navbar navbar-light bg-light flex-column">
<a class="navbar-brand" href="#">Navbar</a>
<nav class="nav nav-pills flex-column">
<a class="nav-link" href="#section-1">Section 1</a>
<a class="nav-link" href="#section-2">Section 2</a>
<a class="nav-link" href="#section-3">Section 3</a>
<a class="nav-link" href="#section-4">Section 4</a>
<!-- Hidden menu items for asides -->
<div class="d-none">
<a class="nav-link" href="#aside-1">Aside 1</a>
<a class="nav-link" href="#aside-2">Aside 2</a>
</div>
</nav>
</nav>
</div>
<div id="content" class="col-9" data-spy="scroll" data-target="#navbar-scollspy">
<div id="section-1">
<h4>Section 1</h4>
<p>...</p>
</div>
<div id="aside-1" class="aside">
<h4>Aside 1</h4>
<p>...</p>
</div>
<div id="section-2">
<h4>Section 2</h4>
<p>...</p>
</div>
<div id="aside-2" class="aside">
<h4>Aside 2</h4>
<p>...</p>
</div>
<div id="section-3">
<h4>Section 3</h4>
<p>...</p>
</div>
<div id="section-4">
<h4>Section 4</h4>
<p>...</p>
</div>
</div>
</div>
</div>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
By the way, you can listen for the activate.bs.scrollspy
event on the spied element ([data-spy="scroll"]
) or any parent, including $('body') and $(document) like this:
$('[data-spy="scroll"]').on('activate.bs.scrollspy', function(event) {
console.log('activate.bs.scrollspy', event);
})