I'm trying to implement smooth scrolling on my website.
However, the scrollbar is not working as expected. It seems like the smooth scrolling and default jumping to anchor links are happening at the same time.
Here is my HTML code for the Bootstrap navigation:
<nav class="navbar fixed-top navbar-expand-sm navbar-light bg-light mb-3" id="main-nav">
<div class="container">
<a class="navbar-brand" href="#">Navbar</a>
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#welcome">Welcome</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#about">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#services">Services</a>
</li>
</ul>
</div>
</nav>
This is the JavaScript code I am using:
<script>
$('body').scrollspy({
target: '#main-nav',
offset: $('#main-nav').outerHeight()
});
// add smooth scrolling
$('#main-nav a').on('click',(event) => {
const sender = event.target; // sender
// check for a hash value
if (sender.hash)
{
// prevent default behaviour
event.preventDefault();
// get sendar hash
const hash = sender.hash;
const navHeight = $('#main-nav').outerHeight();
// animate smooth scroll
$('html').animate({
scrollTop: $(hash).offset().top - (navHeight + 1),
},1500,() => {
// add hash to URL after scroll
this.location.hash = hash;
});
}
});
</script>
And here is the content of the page:
<section id="welcome">
<h3>Welcome</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dicta eaque similique cupiditate! Pariatur, aliquid quae recusandae quidem atque cumque perspiciatis possimus quod repudiandae, labore nobis eius voluptatum! Impedit, sint in.
</p>
</section>
<section id="about">
<h3>About</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dicta eaque similique cupiditate! Pariatur, aliquid quae recusandae quidem atque cumque perspiciatis possimus quod repudiandae, labore nobis eius voluptatum! Impedit, sint in.
</p>
</section>
<section id="services">
<h3>Services</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dicta eaque similique cupiditate! Pariatur, aliquid quae recusandae quidem atque cumque perspiciatis possimus quod repudiandae, labore nobis eius voluptatum! Impedit, sint in.
</p>
</section>
When I click a link in the navigation bar for the first time, it scrolls over the content header making it disappear.
https://i.sstatic.net/axyhK.png
However, when I click the same link again, it scrolls up a little bit and displays the expected result.
https://i.sstatic.net/DZs1I.png
Does anyone know how to fix this issue and make the scrolling work correctly on the first click? Thank you.