Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 12, 2021 03:44 pm GMT

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,  });});

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:


Original Link: https://dev.to/juanbelieni/how-to-create-horizontal-scroll-with-mouse-wheel-using-javascript-4cm5

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To