I am currently working on integrating the scrollspy function from bootstrap 4.1 into my navbar and I have successfully implemented it. However, I am facing challenges in adding smooth scrolling to it. Despite extensive research on the web, I have been unable to resolve this issue.
Below is the code snippet that I am using (borrowed from Bootstrap).
<nav id="navbar-example2" class="navbar navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<ul class="nav nav-pills">
<li class="nav-item">
<a class="nav-link" href="#fat">@fat</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#mdo">@mdo</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Dropdown</a>
<div class="dropdown-menu">
<a class="dropdown-item" href="#one">one</a>
<a class="dropdown-item" href="#two">two</a>
<div role="separator" class="dropdown-divider"></div>
<a class="dropdown-item" href="#three">three</a>
</div>
</li>
</ul>
</nav>
<div data-spy="scroll" data-target="#navbar-example2" data-offset="0">
<h4 id="fat">@fat</h4>
<p>...</p>
<h4 id="mdo">@mdo</h4>
<p>...</p>
<h4 id="one">one</h4>
<p>...</p>
<h4 id="two">two</h4>
<p>...</p>
<h4 id="three">three</h4>
<p>...</p>
</div>
Here is the additional script I attempted to add for achieving smooth scrolling:
<script>
$(document).ready(function() {
$(".nav-item").click(function() {
var target = $(this).attr("href");
$('.active').removeClass('active');
$("html, body").animate({
scrollTop: $(target).offset().top - 50
}, {
duration: 1000,
});
$('body').scrollspy({ target: '#navbar-example2', offset: $(target).offset().top });
$(this).parent().addClass('active');
return false;
});
});
// Navbar fixed position
var distance = $('#site-header').offset().top,
$window = $(window);
$window.scroll(function() {
if ( $window.scrollTop() >= distance ) {
$('#site-header').addClass('fixed-nav')
}
if ( $window.scrollTop() <= distance ) {
$('#site-header').removeClass('fixed-nav')
}
});
$('body').scrollspy({ target: '#navbar-example2', offset: 0 });
</script>
I am currently at a roadblock and struggling to pinpoint where I might be going wrong. Despite attempting various CSS tweaks, I still can't get it to work. Any assistance or suggestions would be greatly appreciated.