How to create horizontal scroll with mouse wheel using JavaScript

juanbelieni

Juan Belieni

Posted on September 12, 2021

How to create horizontal scroll with mouse wheel using JavaScript

Native horizontal scroll with mouse wheel is not so trivial for the user. However, this behavior can be changed using an event listener.

In fact, there are some events involving scrolling and mouse wheel such as mousewheel and DOMMouseScroll. But here I will be using the wheel event.

So, to accomplish this behavior, the JavaScript code will look like this:

element.addEventListener('wheel', (event) => {
  event.preventDefault();

  element.scrollBy({
    left: event.deltaY < 0 ? -30 : 30,
  });
});
Enter fullscreen mode Exit fullscreen mode

Where element is the HTML element that the user will scroll by.

But you can ask why left has static values. That's because different browsers will provide different values for event.deltaY. So it's better to put just one value, only varying when the element is being scrolled to one side or the other.

Result:

💖 💪 🙅 🚩
juanbelieni
Juan Belieni

Posted on September 12, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related