Skip to content

Instantly share code, notes, and snippets.

@raghavdhingra
Created May 28, 2024 14:52
Show Gist options
  • Save raghavdhingra/8f7823ca3b6ce01a599664398891221e to your computer and use it in GitHub Desktop.
Save raghavdhingra/8f7823ca3b6ce01a599664398891221e to your computer and use it in GitHub Desktop.
export const dragElement = (
elementToDrag: HTMLDivElement,
dragButtonRef: HTMLButtonElement,
options?: {
mouseUpCallback?: (e: MouseEvent) => void;
isInScreenDrag?: boolean;
screenElement?: HTMLElement | null;
isDragFullElementOnScreen?: boolean;
}
) => {
const screenElement = options?.screenElement;
const isInScreenDrag = options?.isInScreenDrag;
const mouseUpCallback = options?.mouseUpCallback;
const isDragFullElementOnScreen = options?.isDragFullElementOnScreen;
let pos1 = 0,
pos2 = 0,
pos3 = 0,
pos4 = 0;
if (dragButtonRef) {
dragButtonRef.addEventListener("mousedown", (e) => dragMouseDown(e));
} else if (elementToDrag) {
elementToDrag.addEventListener("mousedown", (e) => dragMouseDown(e));
}
function dragMouseDown(e: MouseEvent) {
e.preventDefault();
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;
}
function elementDrag(e: MouseEvent) {
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:
if (elementToDrag) {
const elementTopOffset = elementToDrag.offsetTop;
const elementLeftOffset = elementToDrag.offsetLeft;
let topVal = elementTopOffset - pos2;
let leftVal = elementLeftOffset - pos1;
// Condition For Keeping Toolbar in Window
if (topVal < 0) {
topVal = 0;
}
if (leftVal < 0) {
leftVal = 0;
}
if (isInScreenDrag) {
const elementHeight = isDragFullElementOnScreen
? 8
: elementToDrag.offsetHeight;
const elementWidth = isDragFullElementOnScreen
? 8
: elementToDrag.offsetWidth;
const windowHeight = screenElement?.clientHeight || window.innerHeight;
const windowWidth = screenElement?.clientWidth || window.innerWidth;
if (topVal + elementHeight > windowHeight) {
topVal = windowHeight - elementHeight;
}
if (leftVal + elementWidth > windowWidth) {
leftVal = windowWidth - elementWidth;
}
}
elementToDrag.style.top = `${topVal}px`;
elementToDrag.style.left = `${leftVal}px`;
}
}
function closeDragElement(e: MouseEvent) {
// stop moving when mouse button is released:
document.onmouseup = null;
document.onmousemove = null;
mouseUpCallback?.(e);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment