Change "scroll to anchor" offset - jquery

15.2k views Asked by At

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;
    }
});
3

There are 3 answers

7
Jean-Paul On BEST ANSWER

It's probably because you are checking on the element's .scrollTop() in the if 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:

if ($('body').scrollTop() > 1400) { ..

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:

// scroll to first anchor
$('a:first').click(function(){
    $('body').animate({
        scrollTop: $( $(this).attr('href') ).offset().top-165
    }, 1400);
});
// scroll to other anchors
$('a:gt(0)').click(function() {
    $('body').animate({
        scrollTop: $( $(this).attr('href') ).offset().top
    }, 1400);
});

This will give a scrollTop offset of 165px only to the first anchor.

See the jsFiddle:

DEMO2

0
gtamborero On

Thanks for the info! I'm doing it without Jquery and seems to work fine over diferent browsers (edge, firefox, chrome)

This is the simple html anchor:

<a class="anchorLink" name="rsc" id="rsc"></a>

And here the magic using negative margin top. Thats perfect when you have sticky headers.

.anchorLink {
      float:left; width:100%; display:block; position:relative; margin-top:-163px;
    }
0
InaFK On

Solution for custom container with scroll:

 var anchor = $('.cust-container-with scroll').find('ul > li > span#unicId');
 var anchorPos = anchor[0].getBoundingClientRect().top;
 var viewPos = $('.cust-container-with scroll')[0].getBoundingClientRect().top;
 var scrollPos = anchorPos - viewPos;

 $('.cust-container-with scroll').animate({scrollTop: scrollPos}, 'slow');