Sometimes the scrolling to anchors is screwed up due to the sticky nav covering the content of the page. To fix this issue, we can apply some math to the ‘scrollTop’ value of an element. Here’s the script that does just that:
<script>
//Adds this to the onload event listener
window.addEventListener(‘load’, function(){
//Gets all links on a page
jQuery(“a”).click(function(){
//gets links that have a hash and are on the same domain.
if (this.hash !== “” && this.pathname === window.location.pathname){
//Prevents the default action
event.preventDefault();
//grabs the current offset, subtracts the value of the topbar. #masthead was the ID of the navbar on one page, so you need to change this to the current page’s navbar ID
newLocation = jQuery(this.hash).offset()[‘top’] – jQuery(“#masthead”).height();
//If, after the subtraction operation, the value is 0, reset to 0
if (newLocation < 0){
newLocation = 0;
}
//Scrolls to the location with the scroll to location function.
scrollToLocation(newLocation);
}
});
});
//Function that animates the scroll
function scrollToLocation(newLocation){
//Performs the scroll via animation for extra oomph.
jQuery(“html, body”).animate({scrollTop: newLocation}, 1000);
}
</script>
