Szabolcs
Szabolcs

Reputation: 1533

How to animate scroll position of div with overflow: auto?

I'm trying to create a function which scrolls given div or body to an element's location within. Currently it looks like:

function scrollTo($elem, offset, delay, $context){
    delay = delay || 800;
    offset = offset || 0;
    $context = $context || $('html, body');
    $context.animate({
        scrollTop: $elem.offset().top-offset
    }, delay);
}

It works fine on body, however, when I give it $context the first call works as intended, but all the consecutive calls are scrolling to a wrong position.

Why is this behavior and how to fix it? FIDDLE

Upvotes: 0

Views: 1201

Answers (1)

stanley1943
stanley1943

Reputation: 877

The offset().top measures the distance from the top of the page to the element.

  • When you click .1, the offset distance to the top of the page is 300.
  • Once .large which is now -300 is scrolled to that position, .1 offset becomes 0, .2 becomes 300, .3 becomes 600.
  • so you need to minus the offset of .large to get the real position.

Code

function scrollTo($elem, offset, delay, $context){
    delay = delay || 800;
    offset = offset || 0;
    $context = $context || $('html, body');
    var a = $context.find('.large'); //need this
    $context.animate({
        scrollTop: $elem.offset().top - a.offset().top
    }, delay);
}

Here is the jsfiddle https://jsfiddle.net/a8jc5q6r/4/

Upvotes: 1

Related Questions