Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/React onClick scroll set amount down/up

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.

like image 321
Johan Jönsson Avatar asked May 31 '26 20:05

Johan Jönsson


2 Answers

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)
}
like image 178
Mayank Bansal Avatar answered Jun 03 '26 10:06

Mayank Bansal


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?

like image 26
pkyo Avatar answered Jun 03 '26 09:06

pkyo