loading...

Divert Vertical Scroll To The Side ↔️

samthor profile image Sam Thorogood ・1 min read

Let's try a combined blog post today: one tip for helping your users get around when you have horizontal scroll areas (for effect, or whatever), and one tip for navigating the web.

Vertical To Horizontal

If you have a great, amazing UI feature which just happens to scroll horizontally: think a big long list of products which go on forever, users can use say, a trackpad or a scroll bar to get there.

But if your user has a regular mouse with only a vertical scroll wheel, how can they navigate that area? 🤷

We can actually redirect catch the wheel event, and just modify the scrollLeft property (which controls horizontal navigation) based on deltaY (the up and down motion of the wheel). We also need deltaX, as otherwise we prevent real horizontal scrolling. Take a look:

// handle up/down scrollwheel on the scroller, as most folks don't have horizontal scroll
scrollableElement.addEventListener('wheel', (ev) => {
  ev.preventDefault();  // stop scrolling in another direction
  scrollableElement.scrollLeft += (ev.deltaY + ev.deltaX);
});

This is something we used on Santa Tracker in the 🧝 Elf Builder game.

The Tip (aka Today I Learned)

If you scroll vertically on a page (in nearly any browser) but hold down shift, you'll actually scroll horizontally.

Thanks!

That's all for today!

18 👋

Posted on by:

samthor profile

Sam Thorogood

@samthor

Developer Relations for Web at Google.

Discussion

markdown guide
 

You have to let the default behaviour for the user who scroll with shift to not lose the scroll inertia

scrollableElement.addEventListener('wheel', (ev) => {
  if (!ev.shiftKey) {
    ev.preventDefault();
    scrollableElement.scrollLeft += ev.deltaY + ev.deltaX;
  }
});

Also when you scroll horizontally on a laptop trackpad, the shiftKey will be set to true.