Skip to content

Instantly share code, notes, and snippets.

@RayLuxembourg
Last active November 14, 2018 08:59
Show Gist options
  • Save RayLuxembourg/6b99b16534ed6e4c6692ee67842c4da8 to your computer and use it in GitHub Desktop.
Save RayLuxembourg/6b99b16534ed6e4c6692ee67842c4da8 to your computer and use it in GitHub Desktop.
Rxjs Universal drag event
export const DragEvent = (selector:string):Observable<boolean> => {
//element where the drag event should be recorded (make sure element is in the dom)
const elem = document.querySelector(selector);
// touch events to handle mobile devices
const touchStart$ = fromEvent<TouchEvent>(elem, 'touchstart');
const touchEnd$ = fromEvent<TouchEvent>(elem, 'touchend');
const touchMove$ = fromEvent<TouchEvent>(elem, 'touchmove');
// mouse events for desktop users
const mouseDown$ = fromEvent<MouseEvent>(elem, 'mousedown');
const mouseUp$ = fromEvent<MouseEvent>(elem, 'mouseup');
const mouseMove$ = fromEvent<MouseEvent>(elem, 'mousemove');
//Mouse drag event
const mouseDragging$ = mouseMove$.pipe(
skipUntil(mouseDown$),
takeUntil(mouseUp$)
);
//
const mapToBoolean = (bool) => map(() => bool);
//universal drag event will emit true on drag (desktop/mobile) optional:add touchStart$ to the merge.
const move$ = merge(mouseDragging$, touchMove$).pipe(mapToBoolean(true);
//universal end of drag event will emit false on drag end (desktop/mobile)
const end$ = merge(mouseUp$, touchEnd$).pipe(mapToBoolean(false);
//merged to return true or false depending on user dragg
return merge(move$, end$).pipe(distinctUntilChanged());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment