Is it possible to change the offset of the scrollTo anchor jQuery?
At the first anchor I want a negative offset of 165px, but after that I don't want any offset.
My idea was something like the code below, but I can't make it work :/
Can anyone help me?
//scroll to anchor
$('a').click(function(){
if ($(this).scrollTop() > 1400) {
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top-165
}, 1400);
return false;
} else {
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 1400);
return false;
}
});
It's probably because you are checking on the element's
.scrollTop()
in theif
statement opposed to the actual body's scroll position. Because the$(this).scrollTop()
is probably static, the if statement won't make a difference.So try:
I've created an example in jsFiddle which demonstrates it works fine if you define the
if
statement correctly:> jsFiddle example <
If you scroll the body further down than 1400px, the scrolltop will scroll to:
$( $(this).attr('href') ).offset().top-165
(the color of the info div will also change color to green; makes it easy to test the setup)
Otherwise it will just scroll to:
$( $(this).attr('href') ).offset().top
That should help you out. Good luck.
Edit
If you only want the first anchor to have an offset, you can apply the following code:
This will give a
scrollTop
offset of 165px only to the first anchor.See the jsFiddle:
DEMO2