Created
May 18, 2021 09:44
-
-
Save nelsonfncosta/6bd7a6e68ffbea3d196db862e1015a42 to your computer and use it in GitHub Desktop.
Make an element Draggable !
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function dragElement(elmnt, dragElement = elmnt) { | |
let pos1 = 0; | |
let pos2 = 0; | |
let pos3 = 0; | |
let pos4 = 0; | |
dragElement.onmousedown = dragMouseDown; | |
function dragMouseDown(e) { | |
e = e || window.event; | |
e.preventDefault(); | |
// Get the mouse cursor position at startup: | |
pos3 = e.clientX; | |
pos4 = e.clientY; | |
document.onmouseup = closeDragElement; | |
// Call a function whenever the cursor moves: | |
document.onmousemove = elementDrag; | |
} | |
function elementDrag(e) { | |
e = e || window.event; | |
e.preventDefault(); | |
// Calculate the new cursor position: | |
pos1 = pos3 - e.clientX; | |
pos2 = pos4 - e.clientY; | |
pos3 = e.clientX; | |
pos4 = e.clientY; | |
// Set the element's new position: | |
elmnt.style.top = `${elmnt.offsetTop - pos2}px`; | |
elmnt.style.left = `${elmnt.offsetLeft - pos1}px`; | |
} | |
function closeDragElement() { | |
// Stop moving when mouse button is released: | |
document.onmouseup = null; | |
document.onmousemove = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment