DEV Community

Discussion on: How to create horizontal scroll with mouse wheel using JavaScript

Collapse
 
kcabral profile image
Kalil Cabral

The point of this for me is to make it less inconvenient for people with a mouse to scroll sideways without bothering people using a trackpad.

The issue with this solution is that if the user actually scrolls left or right, the content will always scrolls right (event.deltaY will be 0).

I also think it's way more natural if scrolling down scrolls the content right.

Here's is how I'd do it:

// Only works if scroll was _started inside the element_.

function force_scroll_sideways(element) {
  element.addEventListener("wheel", (event) => {
    event.preventDefault();

    let [x, y] = [event.deltaX, event.deltaY];
    let magnitude;

    if (x === 0) {
      magnitude = y > 0 ? -30 : 30;
    } else {
      magnitude = x;
    }

    //console.log({ x, y, magnitude });
    element.scrollBy({
      left: magnitude
    });
  });
}
Enter fullscreen mode Exit fullscreen mode