Below is a handy JavaScript widget that lets you define a site-wide scroll offset for anchor links. This means that when you click an anchor link, the browser does not land pixel-perfect at the start of the target element but stops a few pixels before it. This is useful if, for example, you use a fixed header. In the snippet, the height of the offset is derived from the height of the header, plus 20px. You will still need to define the header container in the code yourself.
$(function() {
headerScrollOffset = $('#masthead').height() + 20;
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top - headerScrollOffset
}, 200);
return false;
}
}
});
});
Photo by Lucas Sankey on Unsplash




