I am looking to implement a scrolling feature on the homepage section using jquery. The challenge is that I want the scrolling to work regardless of the page I am currently on.
Here is the HTML code snippet:
<ul>
<li class="nav-item active">
<a href="#home" class="nav-link p-0">Home </a>
</li>
<li class="nav-item">
<a href="#about-us" class="nav-link p-0">About us</a>
</li>
<li class="nav-item">
<a href="#references" class="nav-link p-0">References</a>
</li>
</ul>
And here is the jquery function responsible for animating the scroll:
$(".nav-link").on("click", function (e) {
e.preventDefault();
var target = $(this).attr("href");
$('html, body').animate({scrollTop: $(target).offset().top}, 800, 'linear');
});
When I click on a .nav-link
while on the homepage (www.my-url.com
), it scrolls smoothly as expected. However, if I am on another page like www.my-url.com/some-page
and click on a .nav-link
, the scroll animation does not work.
Is there a way to first navigate to the homepage before applying the scroll animation when clicking from a different page?
Any suggestions would be greatly appreciated.