Skip to content

Instantly share code, notes, and snippets.

@jinjor
Last active March 19, 2019 22:40
Show Gist options
  • Save jinjor/b843d4c84b73ff8f5a50fdff1d21e192 to your computer and use it in GitHub Desktop.
Save jinjor/b843d4c84b73ff8f5a50fdff1d21e192 to your computer and use it in GitHub Desktop.
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