Skip to main content

createDraggableObservable

Types

function createDraggableObservable<GElement extends Element>(
element: Element,
): IObservable<IDraggableObservableNotifications<GElement>>
type IDraggableObservableNotifications<GElement extends Element> =
| IDragStartNotification<GElement>
| IDragMoveNotification<GElement>
| IDragEndNotification<GElement>
;

type IDragStartNotification<GElement extends Element> = INotification<'drag-start', IDraggableElementObject<GElement>>;
type IDragMoveNotification<GElement extends Element> = INotification<'drag-move', IDraggableElementObject<GElement>>;
type IDragEndNotification<GElement extends Element> = INotification<'drag-end', IDraggableElementObject<GElement>>;


interface IDraggableObject {
readonly origin: IPoint2D;
readonly delta: IPoint2D;
}

interface IDraggableElementObject<GElement extends Element> extends IDraggableObject {
readonly element: GElement;
}

interface IPoint2D {
readonly x: number;
readonly y: number;
}

Definition

Creates an Observable that allows us to "drag" an element.

Example

Draggable element

const element: HTMLElement = document.querySelector('.draggable');

const subscribe = createDraggableObservable<HTMLElement>(element);

subscribe((notification: IDraggableObservableNotifications<HTMLElement>) => {
if (isDragMoveNotification(notification)) {
element.style.transform = `translate(${notification.value.delta.x}px, ${notification.value.delta.y}px)`;
}
});