Reputation: 15
I'm trying to improve the anchor scroll code I found as another question's answer. It works great for another page scrolls but scrolls without animation if it's in the same page. The thing is, I would like to have the animation for same page anchors too but I could not figure out how to include it.
$(document).ready(function () {
var urlHash = window.location.href.split("#")[1];
if (urlHash && $('#' + urlHash).length )
$('html,body').animate({
scrollTop: $('#' + urlHash).offset().top - 60
}, 2500);
});
Upvotes: 0
Views: 2226
Reputation: 12402
If you break the code out into its own function, you can then use that function in a click handler to scroll when an anchor link is clicked in addition to using it as the ready handler:
function scrollToAnchor (url) {
var urlHash = url.split('#')[1];
if (urlHash && $('#' + urlHash).length) {
$('html').animate({
scrollTop: $('#' + urlHash).offset().top - 60
}, 2500);
}
}
$(document).ready(function () {
scrollToAnchor(window.location.href);
});
$('.nav-link').click(function (event) {
event.preventDefault(); // stop the browser from snapping to the anchor
scrollToAnchor(event.target.href);
});
.section {
height: 300px;
width: 300px;
border: 1px solid #000;
}
.nav {
right: 10px;
top: 10px;
position: sticky;
display: block;
width: 100%;
height: 1.5em;
background: #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="nav">
<a class="nav-link" href="#a">A</a>
<a class="nav-link" href="#b">B</a>
<a class="nav-link" href="#c">C</a>
<a class="nav-link" href="#d">D</a>
<a class="nav-link" href="#e">E</a>
</div>
<br>
<div class="section" id="a">A</div>
<div class="section" id="b">B</div>
<div class="section" id="c">C</div>
<div class="section" id="d">D</div>
<div class="section" id="e">E</div>
Upvotes: 1
Reputation: 363
Maybe check out W3Schools?
https://www.w3schools.com/howto/howto_css_smooth_scroll.asp#section1
Back when I used smooth scroll for things this code always worked for me
Upvotes: 0