3

I can't seem to get scrolltop to work when my content is inside of a fixed position container that has overflow-y: scroll specified.

Here is my relevant code:

/* some container with many large content blocks inside */
#container {
    position: fixed;
    width: 300px;
    height: 300px;
    overflow-y: scroll;
}

/* button that has a data-path attribute that specifies where the container should scroll to*/
$(".button").on("click", function(){
    var path = $(this).attr("data-path");
    var anchor = $("#" + path);
    var position = anchor.position().top;
    $("#container").animate({scrollTop: position});
});

I believe this fiddle illustrates my dilemma quite well: http://jsfiddle.net/Qndu5/

If you scroll from the top down to an element, it works great. After that, all bets are off. It is completely incapable of scrolling from any position other than the top. It either horribly misses the mark, or scrolls all the way back to the top, even though the position values being fed to it are seemingly correct.

Surely I'm missing something here, but I'm not sure what I am not understanding. Thanks for any help provided!

1 Answer 1

17

What you are missing is the scrollTop when calculating the position, so if the view is already scrolled, that need to be added to the calculation var position = anchor.position().top + $("#container").scrollTop();

http://jsfiddle.net/x36Rm/

Sign up to request clarification or add additional context in comments.

4 Comments

Perfect! I was not understanding that scrollTop expects the absolute position and not the relative one. I was using position() for fear of scrollTop not returning correct values for my elements within the overflowing fixed container. I'm glad the solution was so brief. Thanks for the help.
Perfect answer, you saved my day!
is there a way to do this without the animation?
Late answer but for future reference just replace $("#container").animate({scrollTop: position}); with $("#container").scrollTop(position); if I remember my jQuery correct

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.