Last active
November 14, 2018 08:59
-
-
Save RayLuxembourg/6b99b16534ed6e4c6692ee67842c4da8 to your computer and use it in GitHub Desktop.
Rxjs Universal drag event
This file contains hidden or 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
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