Skip to content

Instantly share code, notes, and snippets.

@tyrostone
Created October 16, 2016 23:23
Show Gist options
  • Save tyrostone/9e1c5183727fef01278353a406d9323d to your computer and use it in GitHub Desktop.
Save tyrostone/9e1c5183727fef01278353a406d9323d to your computer and use it in GitHub Desktop.
Simple Drag and Drop with Observables
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<!-- <button id="button">Click me</button> -->
<div id="parent" style="width:200px; height:200px; background-color:red">
<div id="widget" style="position:absolute; width:150px; background-color: blue; color: white;">
Drag Me!
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.0.6/rx.all.js"></script>
<script src="simpleDragAndDrop.js"></script>
</body>
</html>
var parent = document.getElementById('parent');
var widget = document.getElementById('widget');
var mousedowns = observable.fromEvent(widget, "mousedown");
var parentMouseMoves = observable.fromEvent(parent, "mousemove");
var parentMouseUps = observable.fromEvent(parent, "mouseup");
var drags = mousedowns.map(
function(drag){
return parentMouseMoves.takeUntil(parentMouseUps)
})
.concatAll();
var subscription = drags.forEach(
function onNext(drag) {
widget.style.left = drag.clientX + "px";
widget.style.top = drag.clientY + "px";
},
function onError(error) {
},
function onCompleted() {
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment