This should be a pretty basic question, but i've thrown most of my morning at it, and at this point I'm close to throwing in the towel. I have not even a little bit of js foo -- but I found a nicely commented chunk of code that I'm hoping to use to animate anchor links it is:
$(document).ready(function() {
$('a[href*=#]').bind('click', function(e) {
e.preventDefault(); //prevent the "normal" behaviour which would be a "hard" jump
var target = $(this).attr("href"); //Get the target
var scrollToPosition = $(target).offset().top;
// perform animated scrolling by getting top-position of target-element and set it as scroll target
$('html, body').stop().animate({ scrollTop: scrollToPosition}, 600, function() {
location.hash = target; //attach the hash (#jumptarget) to the pageurl
});
return false;
});
});
I'm trying to get it to land 30px above the offset().top -- I tried
$('html, body').stop().animate({ scrollTop: scrollToPosition -30}, 600,
Which almost works -- it goes to the right place but then bounces back.
I've also tried
scrollTop: $(target).offset().top - 20 },
I've also tried
scrollTop: $(hash).offset().top + $('#access').outerHeight()
Which doesn't seem to change anything.
It seems like the answer might be here: JQuery page scroll issue with fixed header but I just can't quite seem to get it.
I know this is similar to other questions -- but I've gone through what I could find and I'm illiterate enough that I haven't been able to copy/paste in anything that fixes the issue.
I'd be incredibly grateful for a solution.
Many thanks,
Martin
PS
This other chunk of code I found does work but it's stripping the hashtag out, which makes it mostly useless.
$(function(){
$('a[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) {
var targetOffset = $target.offset().top;
$('html,body').animate({scrollTop: targetOffset - 30}, 1000);
return false;
}
}
});
});
See Question&Answers more detail:
os