1

How can I prevents default scrolling and automatically scroll to next item?

For an instance, I have element2 under element1, how can I scroll to element2 position when I scroll down once instead scroll a little bit down.

Or is there any way to scroll down one window/viewport height? Rather than scroll down arbitrary amount.

Huaxin Zhang
  • 53
  • 1
  • 8

1 Answers1

0

Use scrollIntoView to make the page scroll to particular element.

componentDidMount(){ 
   window.addEventListener('scroll',()=> {
            if (this.state.scroll) {
               document.getElementById("element").scrollIntoView({behavior: "smooth"})
            }
        })
     } 
handleClick(){
  document.getElementById("element").scrollIntoView(true)
}
render(){
  return (
     <div>
       <element1 onClick={this.handleClick.bind(this)}></element1>
       <element2 id="element"></element2>
     </div>
  )
}
Root
  • 2,301
  • 1
  • 10
  • 14
  • where should I call handleClick() function? I do not want any button. I just need it will automatically scroll to element when I scroll. – Huaxin Zhang Dec 12 '18 at 08:10
  • 1
    Should I use handleScroll instead of handleClick and onWheel={(e) => this.handleScroll(e)? – Huaxin Zhang Dec 12 '18 at 08:20
  • I have changed my answer.I assume it should be a element like button to trigger the scroll function. – Root Dec 12 '18 at 08:28
  • And you can also add scrollIntoView in componentDidMount.In this circumstance ,you should add something like this.state.scroll to control the scroll function.If not ,the page will continually to scroll to the particular element. – Root Dec 12 '18 at 08:33