I have started with the code from CSS-Tricks and it works well with the offset. The problem is that the site has a fixed header so I need it to apply the offset when navigating to an internal link from another page. Currently it is getting cut off.
$('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-144
}, 1000);
return false;
}
}
});
Any help would be much appreciated. The page in question is http://marketingmo.wpengine.com/services/#brand-development
There is actually no native js function that can prevent the hash anchoring on page load. But there is a good workaround for this and it is found on this SO question. I've used this method before and it works very well.
setTimeout(function() {
var hash = location.hash
if (hash && $(hash).length) {
var target = $(hash).offset().top;
var headerH = $('header').height();
$(window).scrollTop(target - headerH)
/*
//or with animate,
//but you'll need to reset the scrollTop to 0 (the top) first:
$(window).scrollTop(0);
$('html,body').animate({scrollTop:target - headerH}, 1000);
*/
}
}, 1);