Skip to content

Instantly share code, notes, and snippets.

@vielhuber
Last active June 16, 2022 16:28
Show Gist options
  • Save vielhuber/6a894f6fa083949f6a3b4ea4c8a350fe to your computer and use it in GitHub Desktop.
Save vielhuber/6a894f6fa083949f6a3b4ea4c8a350fe to your computer and use it in GitHub Desktop.
on mousewheel vanilla js scroll horizontally #js
document.addEventListener('wheel', function(e)
{
if(e.type != 'wheel')
{
return;
}
let delta = ((e.deltaY || -e.wheelDelta || e.detail) >> 10) || 1;
delta = delta * (-300);
document.documentElement.scrollLeft -= delta;
// safari needs also this
document.body.scrollLeft -= delta;
e.preventDefault();
});
@vielhuber
Copy link
Author

vielhuber commented Jun 24, 2020

Yes, just check the vertical scroll position and don't execute the function above if you passed the end.

Pseudo code:

document.addEventListener('wheel', function(e)
{
  if(e.type != 'wheel')
  {
    return;
  }
  if( scrollPositionIsAtTheEnd ) {
    return;
  }
  let delta = ((e.deltaY || -e.wheelDelta || e.detail) >> 10) || 1;
  delta = delta * (-300);
  document.documentElement.scrollLeft -= delta;    
  // safari needs also this
  document.body.scrollLeft -= delta;    
  e.preventDefault();
});

You then have to also check when you again scroll up, but I leave the implementation to you. :)

@woodydaniel
Copy link

@themevan did you manage to implement that code?
I’m wanting the same functionality but not fully understanding the pseudo code posted.

@vielhuber
Copy link
Author

@woodydaniel the idea is to entirely skip that function and not to call e.preventDefault when you have reached the end.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment