JavaScript for Touch and Dragging Horizontally on Mobile

14 Views Asked by At

I have created three tabs with corresponding copies for each of them. On mobile, the tabs are on one row and are not full width so some of the tabs are hidden out of view. I'd like to be able to drag and scroll the tabs horizontally (without scroll bar).

My HTML code for the tabs are:

<style>
.label-container.scroll-parent {
      width: 80% !important;
      margin: 0 auto;
      overflow-x: hidden;
    }
.label-container.scroll-parent > .scroll-child {
      width: 1200px;
      cursor: pointer;
      display: flex;
      flex-direction: row !important;
    }
</style>
<div class="single-tab label-container scroll-parent">
        <div class="scroll-child">
          <div id="label_1" class="label odd active">
            <h2>Growth</h2>
          </div>
          <div id="label_2" class="label even">
            <h2>Marketing</h2>
          </div>
          <div id="label_3" class="label odd">
            <h2>Talent</h2>
          </div>
        </div>
      </div>

I tried to use the JavaScript from this StackOverflow which works fine on desktop with mouse events. However I need to make this work on mobile so need to switch it to touch events. The JS code from that SO thread is:

let mouseDown = false;
let startX, scrollLeft;
const slider = document.querySelector('.scroll-parent');

const startDragging = (e) => {
  mouseDown = true;
  startX = e.pageX - slider.offsetLeft;
  scrollLeft = slider.scrollLeft;
}

const stopDragging = (e) => {
  mouseDown = false;
}

const move = (e) => {
  e.preventDefault();
  if(!mouseDown) { return; }
  const x = e.pageX - slider.offsetLeft;
  const scroll = x - startX;
  slider.scrollLeft = scrollLeft - scroll;
}

// Add the event listeners
slider.addEventListener('mousemove', move, false);
slider.addEventListener('mousedown', startDragging, false);
slider.addEventListener('mouseup', stopDragging, false);
slider.addEventListener('mouseleave', stopDragging, false);

Only thing I changed above from the original is the targeted element.

As I understand it, this JavaScript won't work because there's no equivalent to a "mousemove" for touch events.

How can I modify the code to make it work for touch events on mobile?

0

There are 0 best solutions below