Created
July 31, 2016 11:21
-
-
Save lemming/1d3a01178eed0cab1cf33ae409654725 to your computer and use it in GitHub Desktop.
Rx draggable example
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
<div id="draggable-block" style="border: 2px solid black; padding: 20px; display:inline-block">Drag me</div> |
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
let draggableBlock = document.getElementById('draggable-block'); | |
let mouseDowns = Rx.Observable.fromEvent(draggableBlock, 'mousedown'); | |
mouseDowns | |
.flatMap(e => { | |
const diffX = e.pageX - parseInt(e.target.style.left || 0); | |
const diffY = e.pageY - parseInt(e.target.style.top || 0); | |
return Rx.Observable.fromEvent(document, 'mousemove') | |
.map(e => ({ | |
x: e.pageX - diffX, | |
y: e.pageY - diffY | |
})) | |
.takeUntil(Rx.Observable.fromEvent(document, 'mouseup')) | |
}) | |
.subscribe(e => { | |
draggableBlock.style.left = e.x + 'px'; | |
draggableBlock.style.top = e.y + 'px'; | |
}); |
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
#draggable-block { | |
position: absolute; | |
text-transform: uppercase; | |
top: 0; | |
left: 0; | |
-webkit-user-select: none; | |
cursor: default; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment