Kawiesh

Dragging Elements - Touch Devices

Feb 21st, 2022 (edited)
1,590
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //IF UNITS OTHER THAN PX
  2. let _dummydiv= create("div");
  3. _dummydiv.id= "dummydiv";
  4. document.body.append(_dummydiv);
  5. let dummydiv= select("#dummydiv");
  6.  
  7. let root= document.documentElement;
  8. let docwidth= Math.max(
  9. root["clientWidth"],
  10. //document.body["scrollWidth"],
  11. //root["scrollWidth"],
  12. document.body["offsetWidth"],
  13. root["offsetWidth"]
  14. );
  15.  
  16. let docheight= Math.max(
  17. root["clientHeight"],
  18. //document.body["scrollHeight"],
  19. //root["scrollHeight"],
  20. document.body["offsetHeight"],
  21. root["offsetHeight"]
  22. );
  23.  
  24. function drag(element,width,height,e){
  25. e.preventDefault();
  26. let touchLocation = e.targetTouches[0];
  27. let x= touchLocation.pageX || e.pageX;
  28. let y= touchLocation.pageY || e.pageY;
  29.  
  30. //PX & VW & OTHER UNITS
  31. dummydiv.style.cssText= `display: none;
  32. width: calc(${docwidth}px - ${width});
  33. height: calc(${docheight}px - ${height})`;
  34.  
  35. let maxwidth= +getComputedStyle(dummydiv).width.replace("px","");
  36. let maxheight= +getComputedStyle(dummydiv).height.replace("px","");
  37.  
  38.  
  39. //PX UNIT ONLY
  40. let maxwidth= docwidth-width;
  41. let maxheight= docheight-height;
  42.  
  43. if(x<=0){
  44. element.style.left= 0;
  45. }
  46. else if(x>=maxwidth){
  47. element.style.left= maxwidth+"px";
  48. }
  49. else element.style.left= x+"px";
  50.  
  51. if(y<=0){
  52. element.style.top= 0;
  53. }
  54. else if(y>=maxheight){
  55. element.style.top= maxheight+"px";
  56. }
  57. else element.style.top= y+"px";
  58.  
  59.  
  60. }
  61.  
  62.  
  63. //Calling the function------------
  64. dragger.ontouchmove= function(e){
  65. drag(element,width,height,e);
  66. };
  67.  
  68. dragger.onmousemove= function(e){
  69. drag(element,width,height,e);
  70. };
  71.  
  72.  
  73. @@@@@@@@@@@@
  74. Parameters:
  75. e=> event (leave as it is)
  76. element=> the target element to be dragged
  77. //Should have position absolute or fixed and
  78. //No declaration for top left right bottom
  79. width=> width of target element
  80. height=> height of target element
  81. //width & height in pixels but leave out the unit
  82.  
  83. dragger=> element that drags the target element
  84. //could be the element itself (element=this)
  85. //could be another element e.g drag button or bar
  86. //that is a child of the the target element
  87. //or sibling element close to the target element
  88.  
  89.  
Add Comment
Please, Sign In to add comment