0

How can I implement scrolling the way it is done on the Twitter web desktop site? There, it is possible to scroll the center column using the mouse wheel from anywhere on the page, even when positioned over fixed elements, or having clicked outside the center column.

To clarify, I am looking for this ability to scroll a particular element from anywhere on the screen, not how to do infinite scrolling.

Analysing the code used by Twitter might take some time...

Ken
  • 212
  • 3
  • 13

1 Answers1

0

So this is an situation like the Twitter Page:

<html>
    <body>
        <div id="scrollThis" style="height: 100px; width: 400px; overflow-y: auto;">
            <h1>Test</h1>
            <h1>Test</h1>
            <h1>Test</h1>
            <h1>Test</h1>
            <h1>Test</h1>
            <h1>Test</h1>
        </div>
    </body>
</html>
<script>
document.addEventListener("wheel", function(event) {
  factor = event.deltaMode === 1 ? 16 : 1;
  delta = factor * event.deltaY || -event.wheelDelta || event.detail;
  document.getElementById("scrollThis").scrollTop = document.getElementById("scrollThis").scrollTop + delta
  });
</script>

What this code does is simply adding a wheel listener to the whole document. The event that is hand over owns a int deltaY. That is an int and says how many pixels you scroll up or down (+57 or -57 in my case). So basically i add this int to scrollTop of the div that should be scrolled down and then it works :)

I hope i could help you

Best regards

Sebastian

Ken
  • 212
  • 3
  • 13
  • Thanks @Sebastian, I will try this - it looks right. I was missing the delta part.. Will accept your answer in the morning! – Ken Nov 22 '20 at 21:47
  • @Ken No Problem :) – Sebastian Brunnert Nov 23 '20 at 16:41
  • I've tried this and I find that my event.deltaY is only 3, which results in a very slowed-down scroll. So I tried `scrollTop+(event.deltaY*18)` to approximate your example. That works perfectly but this can't be the solution. Need some more help... – Ken Dec 04 '20 at 12:18
  • Original answer did not work on Firefox where the Wheel event has a deltaMode property set to 1 (DOM_DELTA_LINE), meaning a scroll unit is a line not a pixel. Increasing deltaY gets it working. Link: [https://github.com/harvesthq/chosen/issues/2823#issuecomment-327711935](https://github.com/harvesthq/chosen/issues/2823#issuecomment-327711935) I edited Sebastian's answer to reflect this. – Ken Dec 04 '20 at 22:07
  • Another good link: https://stackoverflow.com/questions/20110224/what-is-the-height-of-a-line-in-a-wheel-event-deltamode-dom-delta-line – Ken Dec 04 '20 at 22:33
  • Thank you! I just tested this in Chrome – Sebastian Brunnert Dec 05 '20 at 13:32