agentcooper / react-pdf-highlighter

Set of React components for PDF annotation
https://agentcooper.github.io/react-pdf-highlighter/
MIT License
1.04k stars 407 forks source link

How to listen to scroll events #249

Open dingshaohua-com opened 1 year ago

dingshaohua-com commented 1 year ago

How to listen to scroll events

codiejay commented 8 months ago

Any solution yet?

Areeb-dev commented 3 months ago

Any solution yet?

codiejay commented 3 months ago

@Areeb-dev I fixed this but forgot how i did it so I just gave my code to GPT to explain as i dont have the time to fully recollect my though process months back. This is what GPT had to say:

The onScrollChange prop of the PdfHighlighter component is responsible for clearing the URL hash whenever the user scrolls. This is done to ensure that any existing hash (used for scrolling to a specific highlight) is removed when the document is scrolled.

<PdfHighlighter
   ...
   onScrollChange={() => {
      // clear URL hash
      if (window.location.hash) {
         window.location.hash = "";
      }
   }}
   ...
/>

PdfHighlighter scrollRef Prop:

The scrollRef prop of the PdfHighlighter component is used to get a reference to the scroll function, which is stored in viewerScrollTo.current. This allows programmatic scrolling to specific highlights when required.

<PdfHighlighter
   ...
   scrollRef={(scrollTo) => {
      viewerScrollTo.current = scrollTo;
   }}
   ...
/>

UseEffect Hook with pdfElem:

This useEffect hook attaches an event listener to the PDF element (pdfElem[0]). This event listener updates the current page number whenever the user scrolls within the PDF. The getPdfInViewPageNumber function is used to determine which page is currently in view.

useEffect(() => {
   if (pdfElem[0]) {
      pdfElem[0].addEventListener("scroll", () => {
         const pdfInViewNum = getPdfInViewPageNumber();
         setCurrentPdfPage(pdfInViewNum);
      });
   }
}, [totalPage, scale]);

In summary, the handling of scroll events on the PDF is managed through the onScrollChange and scrollRef props of the PdfHighlighter component, as well as the useEffect hook that attaches a scroll event listener to the PDF element.

Areeb-dev commented 3 months ago

Hey @codiejay , Basically I want to get page Number when user scroll the pdf so is it possible by using this library or is there any other approach