DeepBddmovediv

by spgoo

HTML

<div style="align-items: center; display: flex; justify-content: center; padding: 4rem">
    <div class="container">
      <div class="draggable" style="background-Color:red">
      </div>
            <div class="draggable" style="background-Color:blue">
      </div>
       <div class="draggable"></div>

    </div>
</div>

CSS

.draggable {
  width: 200px;
  height: 50px;
  background: green;
}

JavaScript

// autre exemple https://javascript.info/mouse-drag-and-drop 
// https://dev.to/lensco825/making-a-simple-drag-and-drop-with-js-29l2

const d = document.getElementsByClassName("draggable");

for (let i = 0; i < d.length; i++) {
  d[i].style.position = "relative";
}

function filter(e) {
  let target = e.target;

  if (!target.classList.contains("draggable")) {
    return;
  }

  target.moving = true;

  //NOTICE THIS πŸ‘‡ Check if Mouse events exist on users' device
  if (e.clientX) {
    target.oldX = e.clientX; // If they exist then use Mouse input
    target.oldY = e.clientY;
  } else {
    target.oldX = e.touches[0].clientX; // Otherwise use touch input
    target.oldY = e.touches[0].clientY;
  }
  //NOTICE THIS πŸ‘† Since there can be multiple touches, you need to mention which touch to look for, we are using the first touch only in this case

  target.oldLeft = window.getComputedStyle(target).getPropertyValue('left').split('px')[0] * 1;
  target.oldTop = window.getComputedStyle(target).getPropertyValue('top').split('px')[0] * 1;

  document.onmousemove = dr;
  //NOTICE THIS πŸ‘‡
  document.ontouchmove = dr;
  //NOTICE THIS πŸ‘†

  function dr(event) {
    event.preventDefault();

    if (!target.moving) {
      return;
    }
    //NOTICE THIS πŸ‘‡
    if (event.clientX) {
      target.distX = event.clientX - target.oldX;
      target.distY = event.clientY - target.oldY;
    } else {
      target.distX = event.touches[0].clientX - target.oldX;
      target.distY = event.touches[0].clientY - target.oldY;
    }
    //NOTICE THIS πŸ‘†

    target.style.left = target.oldLeft + target.distX + "px";
    target.style.top = target.oldTop + target.distY + "px";
  }

  function endDrag() {
    target.moving = false;
  }
  target.onmouseup = endDrag;
  //NOTICE THIS πŸ‘‡
  target.ontouchend = endDrag;
  //NOTICE THIS πŸ‘†
}
document.onmousedown = filter;
//NOTICE THIS πŸ‘‡
document.ontouchstart = filter;
//NOTICE THIS πŸ‘†