2

I got a problem figuring out how to make a button onClick scroll down for example 30px per click.

say i got two divs with icons like this

<div className="info-container">
    <div className="scroll-icon-container" onClick={scrollUp(30)}>
        <ScrollUpIcon />
    </div>
    <div className="scroll-icon-container" onClick={scrollDown(30)}>
        <ScrollDownIcon />
    </div>
    <p>"Huge amount of text that will need scrolling"</p>
</div>

Then two functions like

scrollUp(number: amountToScroll){
   //Scroll the "info-container" up amountToScroll pixels
}

scrollDown(number: amountToScroll){
   //Scroll the "info-container" down amountToScroll pixels
}

All i could find so far is either in jquery or how to make it scroll to a specific element but i am looking for a set amount to scroll down in pixels % or whatever works.

Johan Jönsson
  • 539
  • 1
  • 10
  • 23

2 Answers2

5

First of all you can either define a variable or state for maintaining the scroll position.

Let us take state as scrollPosition and initialize it to 0.

Now in the scrollUp function:

scrollUp(amountToScroll){
    this.setState({
        scrollPosition : this.state.scrollPosition + amountToScroll
    })
    window.scrollTo(0, this.state.scrollPosition)
}

Now in scrollDown function:

scrollDown(amountToScroll){
    this.setState({
        scrollPosition : this.state.scrollPosition - amountToScroll
    })
    window.scrollTo(0, this.state.scrollPosition)
}
Mayank Bansal
  • 1,755
  • 2
  • 9
  • 22
4

Use window.scrollBy( pixelsToScrollRight, pixelsToScrollDown ) method.

So instead of scrollUp() and scrollDown() methods you can have something like this:

scroll(number: amountToScroll){
  //amount to scroll is negative to scroll up
  window.scrollBy(0 , amountToScroll)
}

If you want to look at scrolling inside a div: How to scroll to an element inside a div?

pkyo
  • 194
  • 12
  • Tried this but nothing happens when i press it. And also doesnt window. make the whole webpage scroll down? i need just the section this is pressed in to scroll its overflow – Johan Jönsson Jan 23 '19 at 10:32