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.

2 Answers 2

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)
}
Sign up to request clarification or add additional context in comments.

Comments

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?

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.