d3wannabe
d3wannabe

Reputation: 1317

jquery animate/scrollTop to multiple anchors inside divs

I'm having a problem implementing relatively complicated auto-scroll functionality on my page. This displays the issue in my code...

http://codepen.io/d3wannabe/pen/XXxdQq

I have multiple divs on my page (blue,red,green in my example) that I not only want to be able to scroll to (which the top 3 buttons in my example achieve perfectly), but I want to be able to scroll WITHIN (which the bottom 3 buttons represent my best attempt at).

The thing I can't figure out, is why the scroll within function works well on my first div ("scrollTo3rdBlueItem" button), but then less accurately with the other divs ("scrollTo3rdRedItem" and "scrollTo3rdGreenItem" buttons). In my full web application (which obviously has more data to scroll through), I basically see that the lower down the page the parent div is positioned, the less accurately I'm able to scroll within it.

I'm struggling to identify much of a pattern though so can't simply try tweaking the offset values. Any ideas what I might be doing wrong here would be hugely appreciated!!

...since I wasn't allowed to post this without quoting code - here's the jquery function you can see in my codepen!

function scrollToParent(parentID){
        $('html,body').animate({scrollTop: $('#'+parentID).offset().top}, 500);
 }
function scrollToChild(parentID, childID){
      //first focus on the parent
  scrollToParent(parentID);

      $('#'+parentID).animate(
        {scrollTop: $('#'+ childID).offset().top - 100}
        , 500);
}

Upvotes: 2

Views: 1035

Answers (1)

Someone
Someone

Reputation: 3568

UPDATE

Answer here was COMPLETETLY wrong. Left here to preserve the comments.

UPDATE 2

Got IT! You need to take in to account the offset of the parent div. Update your scrollToChild function to the below;

  $('#'+parentID).animate(
    {
      scrollTop: $('#'+ childID).offset().top - $('#'+parentID).offset().top
    }, 500);

Upvotes: 1

Related Questions