DEV Community

Sam Thorogood
Sam Thorogood

Posted on

Divert Vertical Scroll To The Side ↔️

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);
Enter fullscreen mode Exit fullscreen mode

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.


That's all for today!

18 👋

Top comments (2)

mr21 profile image
Thomas Tortorini

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) {
    scrollableElement.scrollLeft += ev.deltaY + ev.deltaX;

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

thisi profile image

Hey, and how do I divert horizontal scroll to vertical scroll?