Guest User

Untitled

a guest
Oct 22nd, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. var Draggable = function(element) {
  2. element.addEventListener('mousedown', Draggable.mousedown, false);
  3. document.addEventListener('mouseup', Draggable.mouseup, false);
  4. }
  5. Draggable.mousedown = function(e) {
  6. e.target.style.position = 'relative';
  7. document.addEventListener('mousemove', Draggable.mousemove, false);
  8.  
  9. var startingPosition = Draggable.mouseposition(e);
  10. var targetPostion = Draggable.targetposition(e);
  11.  
  12. Draggable.offset = {
  13. x: targetPostion.x - startingPosition.x,
  14. y: targetPostion.y - startingPosition.y,
  15. }
  16. Draggable.dragging = e.target;
  17. }
  18. Draggable.mousemove = function(e) {
  19. var mouseposition = Draggable.mouseposition(e);
  20. var moveposition = {
  21. x: mouseposition.x + Draggable.offset.x,
  22. y: mouseposition.y + Draggable.offset.y
  23. }
  24.  
  25. Draggable.dragging.style.left = moveposition.x + 'px';
  26. Draggable.dragging.style.top = moveposition.y + 'px';
  27. }
  28. Draggable.mouseup = function(e) {
  29. document.removeEventListener('mousemove', Draggable.mousemove, false);
  30. }
  31. Draggable.targetposition = function(e) {
  32. var extractInt = function(value) {
  33. var n = parseInt(value);
  34. return n == null || isNaN(n) ? 0 : n;
  35. }
  36.  
  37. return {
  38. x: extractInt(e.target.style.left),
  39. y: extractInt(e.target.style.top),
  40. }
  41. }
  42. Draggable.mouseposition = function(e) {
  43. var posx = 0;
  44. var posy = 0;
  45. if (!e) var e = window.event;
  46. if (e.pageX || e.pageY) {
  47. posx = e.pageX;
  48. posy = e.pageY;
  49. }
  50. else if (e.clientX || e.clientY) {
  51. posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
  52. posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
  53. }
  54. return {
  55. x: posx,
  56. y: posy
  57. };
  58. }
  59.  
  60. var draggableDiv = document.getElementById("dragDiv");
  61. var anotherDraggableDiv = document.getElementById("dragAnotherDiv");
  62. Draggable(draggableDiv);
  63. Draggable(anotherDraggableDiv);​
Add Comment
Please, Sign In to add comment