I have a div with fixed height and overflow: scroll and dynamically added content in my React App and when I press a button this code executes. It scrolls always smooth from the top of the div to the element hello . But I want that it scrolls from the current position to the element and not from the start. How can I achieve this? I tried to set i = target.offsetTop but that doesn't do a smooth scroll. Do you know how?
const target = document.getElementById('hello');
var i = window.pageYOffset;
var int = setInterval(function() {
target.parentNode.scrollTo(0, i);
i += 5;
if (i >= (target.offsetTop - target.parentNode.offsetTop)) {
clearInterval(int);
}
}.bind(this), 10);
Joe Clark
Full-stack developer specializing in healthcare IT
I've always used jQuery for this, but nowadays, there's the native scrollIntoView method. I haven't tried this myself, but worth looking at as opposed to rolling your own:
css-tricks.com/snippets/jquery/smooth-scrolling
developer.mozilla.org/en-US/docs/Web/API/Element/…