0

I have many elements in a webpage of my APP.

How to make it so that whenever the cursor is not hovering over any of the scrollable elements, then it will automatically target a designated element?

  • Could you put up a simple snippet to show the sort of thing you mean? And if the target element is outside the viewport do you still want it scrolled to? – A Haworth Jan 31 '22 at 03:45

1 Answers1

2

When the user uses the mouse wheel or the arrow buttons when not on any element that's scrollable (including the <body>), no scroll event is fired. This is also the case when the user attempts to scroll up when at the very top, and when they attempt to scroll down when at the very bottom.

So, a scroll listener won't work. You probably need to instead listen for mouse wheel events instead.

You probably need:

  • A wheel listener on the window (so it listens to all wheel events)
  • From the event's target - the element that the event was dispatched to - determine if it is ever scrollable. Do the same for all parents. While you can do this programatically, to an extent, it'd be easier if you identified which elements are scrollable, and then just check to see if any of the parents match that. if (e.target.closest('.scrollable1, .scrollable2')) return;
  • If that condition is not fulfilled, then the user attempted to scroll when not over a scrollable element - so you can then call .scrollTo on the desired target element.
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320