James Delaney
James Delaney

Reputation: 1776

How to calculate current scroll position in list?

I am trying with pure javascript to get the current scroll position and save it.

After that, I want to scroll it to the saved/current scroll position.

On the list is attached onScroll event, this function is called on event:

// I wanted to get a scrolled position and scroll it into that position
handleScrollPosition = (e) => {
  const container = document.getElementById(this.props.id);
  container.scrollTo(container.offsetLeft - e.scrollOffset, container.offsetTop - e.scrollOffset);
};

But this not work as expected, any advice on how to handle this?

Upvotes: 0

Views: 1182

Answers (1)

Jibin Jacob
Jibin Jacob

Reputation: 141

try this

Get or set the horizontal and vertical scroll position of an element or the document.

Use the properties scrollTop and scrollLeft to get or set the scroll position of an element:

var el = document.querySelector('div');

get scroll position in px

console.log(el.scrollLeft, el.scrollTop);

set scroll position in px

el.scrollLeft = 500;

el.scrollTop = 1000;

Getting the scroll position of the document in px.

var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
scrollTop = window.pageYOffset || document.documentElement.scrollTop;

Setting the document scroll position of the document in px:

document.documentElement.scrollTop = document.body.scrollTop = 1000;
document.documentElement.scrollLeft = document.body.scrollLeft = 500;

More information https://plainjs.com/javascript/styles/get-and-set-scroll-position-of-an-element-26/

Upvotes: 2

Related Questions