O
O
Olga2018-02-02 14:14:26
React
Olga, 2018-02-02 14:14:26

How to catch the moment when the scroll direction changes?

componentDidMount() {
    this.lastScrollPos = getScrollTop();
    window.addEventListener('scroll', this.scrollUpDown);
  }
  componentWillUnmount() {
    window.removeEventListener('scroll', this.scrollUpDown);
  }

scrollUpDown() {
    const scroll =  this.lastScrollPos;
    this.lastScrollPos = getScrollTop();
  
    if (scroll < this.lastScrollPos) {
      this.setState({shownMenu: false});
      console.log('скролим вниз');
      return;
    }
    if (scroll > this.lastScrollPos) {
      this.setState({ shownMenu: true});
      console.log('скролим вниз');
    }
  }

you need to store the value of scrolled pixels in a variable at the moment when the direction of the scroll
changes getScrollTop () - a cross-browser function for determining the number of scrolled pixels

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Olga, 2018-02-02
@melkaya94

I did it like this, depending on the direction of the scroll, the menu is shown or disappears, it also uses a delay of 150px for mobile and 300 px for the rest of the responders
scrollUpDown() {
const isMobile = this.getLayout();
const delay = isMobile ? 150 : 300;
const scroll = this.lastScrollPos;
this.lastScrollPos = getScrollTop();
const direction = this direction; // old direction value
this.direction = (scroll < this.lastScrollPos);
if (direction !== this.direction) {
this.scrollUp = this.lastScrollPos;// scroll value when changing direction
}
if (Math.abs(this.scrollUp - this.lastScrollPos) > delay) {
this.setState({shownMenu: !this.direction});
}
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question