Skip to content

Instantly share code, notes, and snippets.

@siongui
Created February 17, 2013 00:40
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save siongui/4969457 to your computer and use it in GitHub Desktop.
Save siongui/4969457 to your computer and use it in GitHub Desktop.
AngularJS draggable element (position must be absolute)
/**
* @see https://github.com/siongui/palidictionary/blob/master/static/js/draggable.js
* @see http://docs.angularjs.org/guide/compiler
*/
angular.module('draggableModule', []).
directive('draggable', ['$document' , function($document) {
return {
restrict: 'A',
link: function(scope, elm, attrs) {
var startX, startY, initialMouseX, initialMouseY;
elm.css({position: 'absolute'});
elm.bind('mousedown', function($event) {
startX = elm.prop('offsetLeft');
startY = elm.prop('offsetTop');
initialMouseX = $event.clientX;
initialMouseY = $event.clientY;
$document.bind('mousemove', mousemove);
$document.bind('mouseup', mouseup);
return false;
});
function mousemove($event) {
var dx = $event.clientX - initialMouseX;
var dy = $event.clientY - initialMouseY;
elm.css({
top: startY + dy + 'px',
left: startX + dx + 'px'
});
return false;
}
function mouseup() {
$document.unbind('mousemove', mousemove);
$document.unbind('mouseup', mouseup);
}
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment