Using mouse or touch to scroll sideways

CSS
  <style>
    .MyHozScrolledContainer {
      display: flex;
      flex-direction: row;
      gap: 10px;
      overflow-x: auto;
      overflow-y: hidden;
      flex-wrap: nowrap;
      scroll-behavior: smooth;
      -webkit-overflow-scrolling: touch;
      scrollbar-width: none;
      scroll-snap-type: x mandatory;
      cursor: grab;
      user-select: none;
    }
    .MyHozScrolledContainer::-webkit-scrollbar
    {
      display: none;
    }
    .MyHozScrolledContainer:active
    {
      cursor: grabbing;
    }

    .MyHozScrolledItem {
      display: flex;
      flex-direction: column;
      width: 180px;
      white-space: nowrap;
      overflow: hidden;
      padding-left: 5px;
      flex: 0 0 auto;
      scroll-snap-align: start;
      scroll-padding-left: 8px; /*Use this to give a gap to the left edge*/
    }
  </style>
JavaScript
  <script>
    //ALLOW MOUSE TO HORIZONTALL SCROLL THE DIVS (touch already works, but mouse needs code)
    document.addEventListener("DOMContentLoaded", function(event) {

      const container = document.querySelector('.MyHozScrolledContainer');
      let is_down = false;
      let start_x = 0;
      let scroll_left = 0;

      container.addEventListener('mousedown', function(Event)
      {
        is_down = true;
        container.classList.add('Active');
        start_x = Event.pageX - container.offsetLeft;
        scroll_left = container.scrollLeft;
      });

      container.addEventListener('mouseleave', function()
      {
        is_down = false;
        container.classList.remove('Active');
      });

      container.addEventListener('mouseup', function()
      {
        is_down = false;
        container.classList.remove('Active');
      });

      container.addEventListener('mousemove', function(Event)
      {
        if (!is_down)
          return;

        Event.preventDefault();
        const x = Event.pageX - container.offsetLeft;
        const walk = (x - start_x) * 2;
        container.scrollLeft = scroll_left - walk;
      });
    });
  </script>
HTML
  <div class="MyHozScrolledContainer" >
    <div class="MyHozScrolledItem" >

    </div>
    <div class="MyHozScrolledItem" >

    </div>
    <div class="MyHozScrolledItem" >

    </div>
  </div>
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through resources like this. We hope you find it helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support here. If you need help with a problem please use one of the many online forums.

Comments

Your email address will not be published. Required fields are marked *