Last active
March 19, 2019 22:40
-
-
Save jinjor/b843d4c84b73ff8f5a50fdff1d21e192 to your computer and use it in GitHub Desktop.
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
function dragFrom( | |
el: Element, | |
callbacks: { | |
start?: (x: number, y: number) => void; | |
move?: (x: number, y: number) => void; | |
end?: (x: number, y: number) => void; | |
} | |
): () => void { | |
function handleMove(e: MouseEvent) { | |
callbacks.move && callbacks.move(e.clientX, e.clientY); | |
} | |
function handleUp(e: MouseEvent) { | |
unlisten(); | |
callbacks.end && callbacks.end(e.clientX, e.clientY); | |
} | |
function unlisten() { | |
window.removeEventListener("mousemove", handleMove); | |
window.removeEventListener("mouseup", handleUp); | |
} | |
function handle(e: MouseEvent) { | |
callbacks.start && callbacks.start(e.clientX, e.clientY); | |
window.addEventListener("mousemove", handleMove); | |
window.addEventListener("mouseup", handleUp); | |
} | |
el.addEventListener("mousedown", handle); | |
return function() { | |
unlisten(); | |
el.removeEventListener("mousedown", handle); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment