M
M
Maxim Chernykh2019-06-06 11:12:33
Multitouch and gestures
Maxim Chernykh, 2019-06-06 11:12:33

How to drag a container when interacting with its children?

There is such a block . It is 5cf8cad7e844c297315779.png
necessary that it be possible to scroll left to right.
There is a script that works, but if you try to scroll through the child li elements, it does not work.

<ul class="tabs__caption">
  <li class="active">Audi</li>
  <li>Volkswagen</li>
  <li>Mercedes</li>
  <li>BMW</li>
</ul>

var dragItem = document.querySelector(".tabs__caption");
  var container = document.querySelector(".card_links");

  var active = false;
  var currentX;
  var initialX;
  var xOffset = 0;

  container.addEventListener("touchstart", dragStart, false);
  container.addEventListener("touchend", dragEnd, false);
  container.addEventListener("touchmove", drag, false);

  container.addEventListener("mousedown", dragStart, false);
  container.addEventListener("mouseup", dragEnd, false);
  container.addEventListener("mousemove", drag, false);

  function dragStart(e) {
    if (e.type === "touchstart") {
      initialX = e.touches[0].clientX - xOffset;
    } else {
      initialX = e.clientX - xOffset;
    }

    if (e.target === dragItem) {
      active = true;
    }
  }

  function dragEnd(e) {
    initialX = currentX;

    active = false;
  }

  function drag(e) {
    if (active) {

      e.preventDefault();

      if (e.type === "touchmove") {
        currentX = e.touches[0].clientX - initialX;
      } else {
        currentX = e.clientX - initialX;
      }

      xOffset = currentX;

      setTranslate(currentX, dragItem);
    }
  }

  function setTranslate(xPos, el) {
    el.style.transform = "translate3d(" + xPos + "px, 0px, 0px)";
  }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question