Last active
August 29, 2015 14:00
-
-
Save KamilSzot/f326d4593d14d12cd5a9 to your computer and use it in GitHub Desktop.
JavaScript 1.7 mouse drag state machine using generators as coroutines.
This file contains 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
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); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You may need Chrome Canary and "Experimental JavaScript" enabled in chrome://flags/ to run it.