I am working on a UI that uses horizontal scrolling in a div
element (using overflow: scroll
). I cannot scroll to the left, because it would start the
In modern browsers this should do the trick:
element.addEventListener("wheel", function(event) {
if (Math.abs(event.deltaX) < Math.abs(event.deltaY)) {
// Scrolling more vertically than horizontally. Let it be!
return
}
const scrollLeftMax = this.scrollWidth - this.offsetWidth
if (
this.scrollLeft + event.deltaX < 0 ||
this.scrollLeft + event.deltaX > scrollLeftMax
) {
event.preventDefault()
}
}, false)
Side note: Firefox has a handy scrollLeftMax property, but it's not standard, so it's better to calculate it ourselves.