Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
});
like image 383
KeySee Avatar asked May 07 '14 07:05

KeySee


1 Answers

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

like image 134
SW4 Avatar answered Nov 02 '22 08:11

SW4