Using scrollTop inside of a fixed element with overflow-y:scroll

12,692

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/

Share:
12,692
addMitt
Author by

addMitt

Updated on June 04, 2022

Comments

  • addMitt
    addMitt almost 2 years

    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!