Samantha Ingram
Samantha Ingram

Reputation: 114

Store Scroll Position on Scroll Direction Change

I'm working on a react module that handles showing and hiding a state element based on scroll position. What I have is functional, but I need to be able to capture scroll position on direction change.

Here are the relevant code snippets, all bindings and event listeners are functional:

this.state = {
  lastScrollPos: 0,
  down: true
};

_scrollFunction() {
  const thisPos = window.pageYOffset;
  const down = thisPos > this.state.lastScrollPos;

  if (down) {
    this.setState({
      down: true,
      lastScrollPos: thisPos
    });
  } else if (!down) {
    this.setState({
      down: false,
      lastScrollPos: thisPos
    });
  }

}

In _scrollFunction() above, setting lastScrollPos: thisPos gives me the scroll position right before the page scrolled again.

My question is how can I capture the scroll position of when the scroll direction changed. If I'm scrolling down then scroll up, I need to know the place that it occurred and vice versa.

Any advice towards this is appreciated! Thank you!

Upvotes: 0

Views: 1006

Answers (1)

1ven
1ven

Reputation: 7026

You should check in _scrollFunction whether current down value is differs from down value from state. If yes, write thisPos value to changedPos state variable.

Working example:

constructor() {
  super();

  this.state = {
    lastScrollPos: 0,
    changedPos: undefined,
    down: true
  };
}

_scrollFunction() {
  const thisPos = window.pageYOffset;
  const down = thisPos > this.state.lastScrollPos;
  // If current `down` value is differs from `down` from state,
  // assign `thisPos` to variable, else assigning current `changedPos` state value.
  const changedPos = down !== this.state.down ? thisPos : this.state.changedPos;

  this.setState({
    lastScrollPos: thisPos,
    changedPos,
    down
  });
}

Also, I've made working demo on CodePen, you can check it out for additional info.

Upvotes: 1

Related Questions