Skip to content

Instantly share code, notes, and snippets.

@KamilSzot
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KamilSzot/f326d4593d14d12cd5a9 to your computer and use it in GitHub Desktop.
Save KamilSzot/f326d4593d14d12cd5a9 to your computer and use it in GitHub Desktop.
JavaScript 1.7 mouse drag state machine using generators as coroutines.
var $box = $('<div id="box">').appendTo(document.body).css({
width: 100,
height: 100,
position: 'absolute',
left: 100,
top: 100,
background: 'green',
cursor: 'pointer',
border: '5px solid red'
});
function pointInside(mx, my) {
var pos = $box.offset();
var x = pos.left, y = pos.top;
if(!(x <= mx && x+$box.outerWidth() > mx && y <= my && y+$box.outerHeight() > my)) {
return false;
}
return { x: x - mx, y: y - my };
}
function clip(position, max) {
return {
x: Math.min(Math.max(0, position.x), max.x),
y: Math.min(Math.max(0, position.y), max.y)
};
}
var dragging = (function* () {
while(true) {
var e = yield true;
if(e.type === 'mousedown') {
var offset = pointInside(e.pageX, e.pageY);
if(offset) {
while(true) {
e = yield true;
if(e.type == 'mouseup') {
break;
}
var target = clip(
{ x: e.pageX, y: e.pageY },
{
x: $(document).width() - $box.outerWidth(),
y: $(document).height() - $box.outerHeight()
}
);
requestAnimationFrame(function() {
$box.css({ left: target.x, top: target.y });
});
}
}
}
}
})();
dragging.next();
$(document).on('mousedown mouseup mousemove', function(e) {
dragging.next(e);
});
@KamilSzot
Copy link
Author

You may need Chrome Canary and "Experimental JavaScript" enabled in chrome://flags/ to run it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment