KeySee
KeySee

Reputation: 780

JQuery .scrollTop() and .offset().top issue: how it work? How to solve?

I want to achieve some kind of smooth scrolling, so I made this script:

$('a').click(function(){
    var sclink = $(this).attr('href');
    $('.menu').animate({
        scrollTop: $(sclink).offset().top
    }, 500);
    return false;
});

The problem? When I click on the 'a' the offset.top() value changes in another weird value and toggle between them? Why does this happen and how do I resolve it?

http://jsfiddle.net/StartStep/9SDLw/2947/

I think the problem is with the scroll.top() that gets the value in another way... jsfiddle.net/9SDLw/2950/

$('a').click(function(){
    var sclink = $(this).attr('href');
    $('.menu').animate({
        scrollTop: $(sclink).position().top
    }, 500);
    logit('Anchor: '+sclink+'; Offset top value: <b>'+$(sclink).offset().top+'</b>')
    return false;
});

Upvotes: 5

Views: 10392

Answers (1)

SW4
SW4

Reputation: 71150

Use position instead of offset.

The reason is offset is relative to the viewport, as such it looks like you've scrolled too far, but this is because the top of your viewport area is being obscured by your layout, so offset is actually not what you want, instead, position is.

You should also add a reference to stop before calling animate to ensure if a user clicks in quick succession the behaviour is as expected (the animation queue is essentially flushed)

With that in mind your HTML also needs some work- the clickable link hasnt got closing tags for example.

Change your scrolling code to:

$('.menu').stop(true,true).animate({
    scrollTop: $(sclink).position().top
}, 500);

Demo Fiddle

Upvotes: 6

Related Questions