Search code examples
reactjstypescriptscrollbar

Is there a way to detect if the user has clicked the scrollbar in typescript?


I am working on a react application, where i am using window.addEventListener('mousedown', ...) to detect if the user has clicked on the window. However i do not want this event to trigger, when the user clicks on the scrollbar. Is there a way to detect if the user has clicked the scrollbar?

I tried to detect the scrollbar by checking if document.body.clientWidth < event.offsetX inside of the 'mousedown' event listener. Sadly, this did not work. I also tried to get the width of the scrollbar by subtracting widths of certain elements expecting to get the width of the scrollbar. I also tried using the react-scrollbar-size library.

This always resulted in the scrollbar having a width of 0px, and therefore it wasn't possible to detect if the user has clicked the scrollbar using this method.


Solution

  • Use click event instead:

    window.addEventListener("click", () => console.log("click"));