Reputation: 1533
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
Reputation: 877
The offset().top
measures the distance from the top of the page to the element.
.1
, the offset distance to the top of the page is 300
..large
which is now -300
is scrolled to that position, .1
offset becomes 0
, .2
becomes 300, .3
becomes 600
..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