Bootstrap 5 Scrollspy with nested nav
Last Updated :
25 Jul, 2024
Bootstrap 5 Scrollspy is one of the features which targets the navigation bar contents automatically on scrolling the area. The navigation highlights the navbar links as the user scrolls the page. Only nav or list groups may be utilized with Scrollspy. Scrollspy can work with a simple navbar and also a nested navbar.
A nested navbar is one in which there is one whole navbar inside the already existing parent navbar. We can add the ms-* class to the elements of the nested navbar to add a better experience and interface where * can take values from 1 to 9.
Syntax:
<nav id="navbarExample" class="navbar">
<a class="navbar-brand" href="#cl-1">Navbar</a>
<nav class="nav">
<nav class="nav">
...
</nav>
</nav>
</nav>
<div data-bs-spy="scroll" data-bs-target="#navbarExample">
<div id="cl-1">...</div>
...
</div>
There is no usage of any distinct class or attribute for this, we just need to enclose one navbar inside another to make this happen.
Example 1: The code example below demonstrates how we can create a side navigation bar that has nested nav and options.
HTML
<!doctype html>
<html lang="en">
<head>
<link href=
"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity=
"sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">
<script src=
"https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity=
"sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous">
</script>
<script>
$(function(){
$('#work').on('activate.bs.scrollspy')
});
</script>
<style>
body
{
position: relative;
}
</style>
</head>
<body class="m-2">
<h1 class="ms-5 text-success">
GeeksforGeeks
</h1>
<h4 class="ms-5">Bootstrap 5 Scrollspy with nested nav
</h4>
<nav class="container-fluid navbar navbar-expand-sm
navbar-light bg-light" id="scrollspy">
<a class="nav-link active" href="#dataStructs">
Data Structures</a>
<a class="nav-link" href="#algo">
Algorithms</a>
<nav class="navbar" id="scrollspy">
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle ms-4 my-1"
type="button"
id="dropdownMenuButton1"
data-bs-toggle="dropdown"
aria-expanded="false" href="#other">
Other Navbar
</button>
<ul class="dropdown-menu bg-dark" aria-labelledby="dropdownMenuButton1">
<nav class="navbar navbar-expand-sm navbar-dark bg-dark"
id="scrollspy&