Search code examples
jqueryanchoroffsetscrollto

Change "scroll to anchor" offset - jquery


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

Solution

  • 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