Skip to content

Instantly share code, notes, and snippets.

@nelsonfncosta
Created May 18, 2021 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nelsonfncosta/6bd7a6e68ffbea3d196db862e1015a42 to your computer and use it in GitHub Desktop.
Save nelsonfncosta/6bd7a6e68ffbea3d196db862e1015a42 to your computer and use it in GitHub Desktop.
Make an element Draggable !
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