Kawiesh

Draggable

Jun 19th, 2021 (edited)
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //------------------------DRAGGABLE ELEMENT TOUCH------------------------------
  2.  
  3. let dragItem= document.querySelector("#item");
  4. var container= document.querySelector("#container");
  5.  
  6. let active= false;
  7. let currentX; let currentY;
  8. let initialX; let initialY;
  9. let xOffset= 0; let yOffset = 0;
  10.  
  11. container.addEventListener("touchstart", dragStart, false);
  12. container.addEventListener("touchend", dragEnd, false);
  13. container.addEventListener("touchmove", drag, false);
  14.  
  15. container.addEventListener("mousedown", dragStart, false);
  16. container.addEventListener("mouseup", dragEnd, false);
  17. container.addEventListener("mousemove", drag, false);
  18.  
  19. function dragStart(e) {
  20. if (e.type === "touchstart"){
  21. initialX= e.touches[0].clientX - xOffset;
  22. initialY= e.touches[0].clientY - yOffset;
  23. }
  24. else{
  25. initialX= e.clientX - xOffset;
  26. initialY= e.clientY - yOffset;
  27. }
  28.  
  29. if (e.target === dragItem) active= true;
  30. }
  31.  
  32. function dragEnd(e) {
  33. initialX = currentX;
  34. initialY = currentY;
  35. active = false;
  36. }
  37.  
  38. function drag(e) {
  39. if (active) {
  40. e.preventDefault();
  41. if (e.type === "touchmove") {
  42.    currentX= e.touches[0].clientX - initialX;
  43.    currentY= e.touches[0].clientY - initialY;
  44.    }
  45.    else{
  46.    currentX = e.clientX - initialX;
  47.    currentY = e.clientY - initialY;
  48.    }
  49.  
  50.    xOffset = currentX; yOffset = currentY;
  51.  
  52.    setTranslate(currentX, currentY, dragItem);
  53. }
  54. }
  55.  
  56. function setTranslate(xPos, yPos, el) {
  57. el.style.transform= `translate3d(${xPos}px,${yPos}px,0)`;
  58. }
  59.  
  60.  
  61. //Taken from: https://codepen.io/deanha/pen/zYOprQd
Advertisement
Add Comment
Please, Sign In to add comment