Skip to content

Instantly share code, notes, and snippets.

@KarateJB
Forked from siongui/draggable.js
Created September 12, 2016 09:35
Show Gist options
  • Save KarateJB/7ea4c499928f0ff39eb30e6c76d7784b to your computer and use it in GitHub Desktop.
Save KarateJB/7ea4c499928f0ff39eb30e6c76d7784b 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