skip to Main Content

I have an overlay div that when I scroll it works as expected, but I intend to change the scroll bar movement. So when I move the content to the right, the scroll bar should move to the left (and not with the default behaviour). How can I achieve this?

2

Answers


  1. To achieve a custom scrollbar behavior where it moves in the opposite direction of the content scroll, you can use JavaScript to listen for scroll events and update the scrollbar position accordingly. Here’s an example of how you can accomplish this:

    HTML:

    <div id="overlay">
      <!-- Content -->
    </div>
    

    JavaScript:

    const overlay = document.getElementById('overlay');
    
    overlay.addEventListener('scroll', function() {
      // Calculate the scrollbar position as a percentage
      const maxScrollLeft = overlay.scrollWidth - overlay.clientWidth;
      const scrollPercentage = (overlay.scrollLeft / maxScrollLeft) * 100;
    
      // Calculate the new scrollbar position in the opposite direction
      const newScrollLeft = (100 - scrollPercentage) * maxScrollLeft / 100;
    
      // Update the scrollbar position
      overlay.scrollLeft = newScrollLeft;
      });
    

    In this example, we listen for the scroll event on the overlay element. When the user scrolls, we calculate the scrollbar position as a percentage by dividing the current scroll left value by the maximum scroll left value. Then we calculate the new scroll left value in the opposite direction by subtracting the scroll percentage from 100 and multiplying it by the maximum scroll left value divided by 100. Finally, we update the scrollbar position by setting the scrollLeft property of the overlay element to the new scroll left value.

    Login or Signup to reply.
  2. I’d recommend looking at this article on geeksforgeeks.org by Aditya Taparia, where he walks you through how to do it using plain CSS step-by-step: https://www.geeksforgeeks.org/how-to-change-the-position-of-scrollbar-using-css/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search