porFavor
porFavor

Reputation: 413

How can I find the current scroll position of a chart in Javascript?

I have a chart that is scrollable

enter image description here

I am trying to fire off a function when the user has reached the bottom of the table bordered in red.

The approach I took is to find the height of the chart which is 1520px.

Then I will need a way to find the pixel of the current scroll position, but there is no such method as element.currentScrollPosition

How can I find the current scroll position of the chart?

I will be subtracting the position from 1520px to see if the user has scrolled to the bottom if the result is 0.

This is the code for each row:

function getScrollPosition() {
    const plTable = document.getElementById('plTable');
    const x = plTable?.scrollHeight;
    const y = plTable?.scrollTop;
    const z = plTable?.offsetHeight;
    console.log(x);
    console.log(y); // scroll position from top
    console.log(z);
  }


// chart component

return (
  //... skip some code
</TableHead>
                  <TableBody>
                    <div
                      id="plTable"
                      onClick={getScrollPosition}
                      style={{ border: '1px solid red' }}
                    >
                      {lineItems.map((lineItem, i) => (
                        <TableRow key={lineItem.id}>
                          <LineItemRow
                            i={i}
                            id={lineItem.id}
                            reportName={reportName}
                            level={lineItem.level}
                          />
                        </TableRow>
                      ))}
                    </div>
                  </TableBody>
                </Table>
              </Scrollbar>
            </CardContent>
          </Card>
)

I didn't find scrollTop and offsetHeight too useful, so you can ignore that.

Also scrollTop always gives 0 no matter where I scroll then click

Upvotes: 1

Views: 296

Answers (1)

olabie
olabie

Reputation: 24

The best way to deal with scrolling is by using an Observer API it is better for your website performance.

This is what you must do:

//Add an elemnt in your html with the class of "end" at the end of the chart
//I recommend adding an empty div with the class of "end" and setting it's opacity to 0
const end =document.querySelector(".end");

const endObserver = new IntersectionObserver(function(entries){
    const [entry] = entries;
    if(entry.isIntersecting === false)
    {
    //Put what you want to happen if the end is NOT visible
    }
    else{
    //Put what you want to happen if the end is visible
    //For instance firing your function
    }
    },{root:null,threshold:1});
endObserver.observe(end);

Upvotes: 1

Related Questions