-
Notifications
You must be signed in to change notification settings - Fork 0
/
drag-and-drop-rxjs.html
43 lines (39 loc) · 1020 Bytes
/
drag-and-drop-rxjs.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!doctype html>
<style>
html,
body {
margin: 0;
padding: 0;
height: 100%;
}
#draggable {
cursor: pointer;
position: absolute;
left: 50%;
top: 50%;
width: 100px;
height: 100px;
background: black;
}
</style>
<div id="draggable"></div>
<script src="https://unpkg.com/@reactivex/rxjs@5.0.0/dist/global/Rx.js"></script>
<script>
const draggable = document.getElementById('draggable');
const mousedown = Rx.Observable.fromEvent(draggable, 'mousedown');
const mousemove = Rx.Observable.fromEvent(document, 'mousemove');
const mouseup = Rx.Observable.fromEvent(document, 'mouseup');
mousedown.flatMap(md => {
const startX = md.clientX - draggable.offsetLeft;
const startY = md.clientY - draggable.offsetTop;
return mousemove.map(event => {
return {
left: event.clientX - startX,
top: event.clientY - startY
}
}).takeUntil( mouseup );
}).subscribe(pos => {
draggable.style.left = pos.left + 'px';
draggable.style.top = pos.top + 'px';
});
</script>