script.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*The solution to draggable elements was inspired by w3schools solution on creating a [Draggable HTML Element](https://www.w3schools.com/howto/howto_js_draggable.asp).*/
  2. dragElement(document.getElementById('plant1'));
  3. dragElement(document.getElementById('plant2'));
  4. dragElement(document.getElementById('plant3'));
  5. dragElement(document.getElementById('plant4'));
  6. dragElement(document.getElementById('plant5'));
  7. dragElement(document.getElementById('plant6'));
  8. dragElement(document.getElementById('plant7'));
  9. dragElement(document.getElementById('plant8'));
  10. dragElement(document.getElementById('plant9'));
  11. dragElement(document.getElementById('plant10'));
  12. dragElement(document.getElementById('plant11'));
  13. dragElement(document.getElementById('plant12'));
  14. dragElement(document.getElementById('plant13'));
  15. dragElement(document.getElementById('plant14'));
  16. /*"A closure is the combination of a function bundled together (enclosed)
  17. with references to its surrounding state (the lexical environment).
  18. In other words, a closure gives you access to an outer function’s scope
  19. from an inner function." Create a closure so that you can track the dragged element*/
  20. function dragElement(terrariumElement) {
  21. //set 4 positions for positioning on the screen
  22. let pos1 = 0,
  23. pos2 = 0,
  24. pos3 = 0,
  25. pos4 = 0;
  26. terrariumElement.onpointerdown = pointerDrag;
  27. function pointerDrag(e) {
  28. e.preventDefault();
  29. console.log(e);
  30. // get the initial mouse cursor position for pos3 and pos4
  31. pos3 = e.clientX;
  32. pos4 = e.clientY;
  33. // when the mouse moves, start the drag
  34. document.onpointermove = elementDrag;
  35. // when the mouse is lifted, stop the drag
  36. document.onpointerup = stopElementDrag;
  37. }
  38. function elementDrag(e) {
  39. // calculate the new cursor position
  40. // pos1 = where the Xmouse WAS - where it IS
  41. pos1 = pos3 - e.clientX;
  42. // pos2 = where the Ymouse WAS - where it IS
  43. pos2 = pos4 - e.clientY;
  44. //reset pos3 to current location of Xmouse
  45. pos3 = e.clientX;
  46. //reset pos4 to current location of Ymouse
  47. pos4 = e.clientY;
  48. console.log(pos1, pos2, pos3, pos4);
  49. // set the element's new position:
  50. terrariumElement.style.top = terrariumElement.offsetTop - pos2 + 'px';
  51. terrariumElement.style.left = terrariumElement.offsetLeft - pos1 + 'px';
  52. }
  53. function stopElementDrag() {
  54. // stop calculating when mouse is released
  55. document.onpointerup = null;
  56. document.onpointermove = null;
  57. }
  58. }