Home > Software engineering >  How to have a horizontal scroll work in website with the scroll width set to 0?
How to have a horizontal scroll work in website with the scroll width set to 0?

Time:08-01

I want the user to be able to scroll in the web view like they can drag to scroll on mobile

enter image description here


But is there any way to make it scroll on the web as it does in the mobile view with a drag?

I just want my horizontal UI to be neat and clean without a scroll bar but I can't have it be draggable in the web

I think netflix had navigation arrows in their web app. Is it the only way to create a horizontal scroll UI in web?

CodePudding user response:

For users with a mouse (as is typical with users on desktop) you can scroll horizontally without scrollbars if you have a mouse wheel – you hover over the scrollable element, hold shift and then scroll on the mouse wheel.

If you would like to emulate touch-screen drag scrolling, you would need to use JavaScript, something like this:

let pointerFrom = 0;
let elementFrom = 0;

const scrollable = document.querySelector('.wrapper');

const onDrag = (event) => {
  // Ensure we only do this for pointers that don't have native
  // drag-scrolling behavior and when the pointer is down.
  if (event.pointerType == 'mouse') {
    scrollable.scrollLeft = elementFrom - event.clientX   pointerFrom;
  }
};

scrollable.addEventListener('pointerdown', (event) => {
  // Ensure we only do this for pointers that don't have native
  // drag-scrolling behavior.
  if (event.pointerType == 'mouse') {
    pointerDown = true;
    // Set the position where the mouse is starting to drag from.
    pointerFrom = event.clientX;
    // Set the position of the element is scrolled from.
    elementFrom = scrollable.scrollLeft;

    // React on pointer move.
    document.addEventListener('pointermove', onDrag);
  }
});

// Stop reacting on pointer move when pointer is no longer clicked.
document.addEventListener('pointerup', (event) => {
  // Ensure we only do this for pointers that don't have native
  // drag-scrolling behavior.
  if (event.pointerType == 'mouse') {
    document.removeEventListener('pointermove', onDrag);
  }
});
    
.wrapper {
  display: flex;
  gap: 100px;
  overflow: scroll;
}

.wrapper::-webkit-scrollbar {
  width: 0px;
}
<div >
  <div style="width: 50px;">box 1</div>
  <div style="width: 50px;">box 2</div>
  <div style="width: 50px;">box 3</div>
  <div style="width: 50px;">box 4</div>
  <div style="width: 50px;">box 5</div>
  <div style="width: 50px;">box 6</div>
  <div style="width: 50px;">box 7</div>
  <div style="width: 50px;">box 8</div>
  <div style="width: 50px;">box 9</div>
</div>

With a mouse, there is some conflicting behavior; dragging with the left mouse button held down normally selects text, so you may need to resolve this conflict with extra code.

  • Related