| 21 | from an inner function." Create a closure so that you can track the dragged element*/ |
| 22 | |
| 23 | function dragElement(terrariumElement) { |
| 24 | //set 4 positions for positioning on the screen |
| 25 | let pos1 = 0, |
| 26 | pos2 = 0, |
| 27 | pos3 = 0, |
| 28 | pos4 = 0; |
| 29 | terrariumElement.onpointerdown = pointerDrag; |
| 30 | |
| 31 | function pointerDrag(e) { |
| 32 | e.preventDefault(); |
| 33 | console.log(e); |
| 34 | // get the initial mouse cursor position for pos3 and pos4 |
| 35 | pos3 = e.clientX; |
| 36 | pos4 = e.clientY; |
| 37 | // when the mouse moves, start the drag |
| 38 | document.onpointermove = elementDrag; |
| 39 | // when the mouse is lifted, stop the drag |
| 40 | document.onpointerup = stopElementDrag; |
| 41 | } |
| 42 | |
| 43 | function elementDrag(e) { |
| 44 | // calculate the new cursor position |
| 45 | // pos1 = where the Xmouse WAS - where it IS |
| 46 | pos1 = pos3 - e.clientX; |
| 47 | // pos2 = where the Ymouse WAS - where it IS |
| 48 | pos2 = pos4 - e.clientY; |
| 49 | //reset pos3 to current location of Xmouse |
| 50 | pos3 = e.clientX; |
| 51 | //reset pos4 to current location of Ymouse |
| 52 | pos4 = e.clientY; |
| 53 | console.log(pos1, pos2, pos3, pos4); |
| 54 | // set the element's new position: |
| 55 | terrariumElement.style.top = terrariumElement.offsetTop - pos2 + 'px'; |
| 56 | terrariumElement.style.left = terrariumElement.offsetLeft - pos1 + 'px'; |
| 57 | } |
| 58 | |
| 59 | function stopElementDrag() { |
| 60 | // stop calculating when mouse is released |
| 61 | document.onpointerup = null; |
| 62 | document.onpointermove = null; |
| 63 | } |
| 64 | } |