Created
March 22, 2012 04:54
-
-
Save mattpodwysocki/2156153 to your computer and use it in GitHub Desktop.
Drag and Drop in RxJS
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
<!DOCTYPE html> | |
<head> | |
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script> | |
<script src="rx.min.js" type="text/javascript"></script> | |
<script src="rx.jquery.js" type="text/javascript"></script> | |
<script type="text/javascript"> | |
$(function () { | |
var dragTarget = $('#dragTarget') | |
// Get the three major events | |
, mouseup = dragTarget.onAsObservable('mouseup') | |
, mousemove = dragTarget.onAsObservable('mousemove') | |
, mousedown = dragTarget.onAsObservable('mousedown').select(function (event) { | |
// calculate offsets when mouse down | |
event.preventDefault(); | |
return { left: event.clientX - dragTarget.offset().left, top: event.clientY - dragTarget.offset().top }; | |
}) | |
// Combine mouse down with mouse move until mouse up | |
, mousedrag = mousedown.selectMany(function(imageOffset) { | |
return mousemove.select(function (pos) { | |
// calculate offsets from mouse down to mouse moves | |
return { | |
left: pos.clientX - imageOffset.left, top: pos.clientY - imageOffset.top | |
}; | |
}).takeUntil(mouseup); | |
}); | |
mousedrag.subscribe (function (pos) { | |
// Update position | |
$('#dragTarget').css({top: pos.top, left: pos.left}); | |
}); | |
}); | |
</script> | |
</head> | |
<body> | |
<div id="dragTarget" | |
style="background-color: #000000; border: 1px solid #666666; | |
color: #ffffff; padding: 10px; position: absolute; | |
font-family: sans-serif; cursor: move"> | |
Drag Me! | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You're script looks good but the mousemove should be on
document
:)mousemove = $(document).onAsObservable('mousemove')
because when you're leaving thedragTarget
node with your mouse the event stops 👍