Reputation: 39
I am using the the jQuery animate function for smooth scrolling inside a div however this function only works properly when you are scrolled at the top. after many console logs on the positions of the tags and hours trying to figure this out i know why this is. this is due to the position of the elements inside the overflow changing when you scroll.
the problem is that when you click on one of the tags it will only scroll to the correct position if the div is scrolled to the top, however if the div is anywhere but the top it doesn't do so. for example if you click on the 4th tag and then immediately click on the 3rd it wont go to the correct position when you click on the 3 due to you not being scrolled to the top. i couldn't come up with the correct equation or something to make the div scroll to the correct tag regardless of scroll position. Here is the simple code for the animation the rest is on jsfiddle
$('#iddescription').animate({
scrollTop: target.position().top - $('#iddescription').position().top
}
I did think about doing double animations scrolling to the top first and then scrolling to the correct position but this isn't really what I want.
Could somebody help me please without using a plugin just jQuery, here is the code https://jsfiddle.net/509k8stu/3/ .
Upvotes: 1
Views: 3506
Reputation: 3852
Animating scrollTop
to the following position seems to fix the issue:
target.offset().top
+ $('#iddescription').scrollTop()
- $('#iddescription').offset().top
I would also recommend you abort previous scroll animations using the .stop()
method. So your full animation method would look something like this:
$('#iddescription').stop().animate({
scrollTop: target.offset().top
+ $('#iddescription').scrollTop()
- $('#iddescription').offset().top
}, 1000, function() {
});
See the result in this updated fiddle
Upvotes: 2
Reputation: 2482
You need to get the current scroll top and then add the element.position.top() to it like so:
// Does a scroll target exist?
if (target.length) {
// Only prevent default if animation is actually gonna happen
event.preventDefault();
var $currScrollTop = $("#iddescription").scrollTop();
$('#iddescription').animate({
scrollTop: $currScrollTop + target.position().top - $('#iddescription').position().top
}, 1000, function() {
});
}
Upvotes: 0