Sign in
Log inSign up

Scroll from current position to the element.

DK's photo
DK
·Dec 10, 2017

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);
Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct