skip to Main Content

I have a horizontal scrolling website where I want to take the users’ Y-scrolling input to convert it into X-scrolling. The website already works perfectly when using a trackpad and scrolling on the X axis, so I just want it to work the other way around. Thanks!

This is what I’m trying to workshop but I’m very new to this and it’s probably very wrong:

 <script>
        let invertedscroll = window.ScrollY;
            
        window.addEventListener('scroll', (scrollY) );
        
        function invertscroll (scrollY) {
            window.scrollY = window.scrollX;
        }
        </script>

2

Answers


  1. Use window.scrollTo and invertScroll instead of "scrollY" which is undefined in your implementation:

    <script>
        window.addEventListener('scroll', invertScroll);
    
        function invertScroll(event) {
          event.preventDefault();
          window.scrollTo(window.scrollY, 0);
        }
    </script>
    
    Login or Signup to reply.
  2. Another solution would be to set scrollLeft directly to the <html> when scrolling using the wheel event.
    And don’t forget to call event.preventDefault() to prevent vertical scroll

    document.documentElement.addEventListener('wheel', (event) => {
        event.preventDefault() // prevent vertical scroll
        document.documentElement.scrollLeft += event.deltaY
    })
    body {
      display: flex;
      margin: 0;
    }
    section {
      height: 150px;
      min-width: 50vw;
      background: blue;
    }
    section:nth-child(odd) {
      background: red;
    }
    <section></section>
    <section></section>
    <section></section>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search