Skip to content

Instantly share code, notes, and snippets.

@amowu
Last active February 17, 2017 03:10
Show Gist options
  • Select an option

  • Save amowu/25d4955edd51b5a5455d54240989adc9 to your computer and use it in GitHub Desktop.

Select an option

Save amowu/25d4955edd51b5a5455d54240989adc9 to your computer and use it in GitHub Desktop.
Drag and drop with RxJS
const body = document.body;
const draggableElement = document.getElementById('drag');
const mouseDown$ = Rx.Observable.fromEvent(draggableElement, 'mousedown');
const mouseUp$ = Rx.Observable.fromEvent(body, 'mouseup');
const mouseMove$ = Rx.Observable.fromEvent(body, 'mousemove');
mouseDown$
.map(event => mouseMove$.takeUntil(mouseUp$))
.concatAll()
.map(event => ({ x: event.clientX, y: event.clientY }))
.subscribe(pos => {
draggableElement.style.left = pos.x + 'px';
draggableElement.style.top = pos.y + 'px';
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment