Skip to content

Instantly share code, notes, and snippets.

@akcoder
Last active November 29, 2016 19:58
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 akcoder/b0f11973667217aeb41c79e37fcb9b6c to your computer and use it in GitHub Desktop.
Save akcoder/b0f11973667217aeb41c79e37fcb9b6c to your computer and use it in GitHub Desktop.
modal-draggable directive for Angular1. Allows UIB modal dialogs to be dragged around the screen. Does bounds checking to prevent the window from being dragged off screen.
(function (angular) {
"use strict";
modalDraggable.$inject = ['$window', '$document', '$interval', '$log'];
angular.module('apt.widgets')
.directive('modalDraggable', modalDraggable);
function modalDraggable($window, $document, $interval, $log) {
return function (scope, element) {
var startX = 0;
var startY = 0;
var x = 0;
var y = 0;
var headerHeight = 0;
var draggable = angular.element(element.parents('.modal-dialog')[0]);
var topMargin = parseInt(draggable.css('margin-top'), 10);
var header = draggable.find('.modal-header');
//Have to grab the x position after the element is visible, otherwise the value will be 0
var intervalHandle = $interval(function () {
if (draggable.offset().left) {
$interval.cancel(intervalHandle);
x = draggable.offset().left;
draggable.css({
position: 'fixed',
left: x
});
}
}, 50);
header.css('cursor', 'move')
.on('mousedown', function (event) {
if (event.button !== 0) {
return;
}
// Prevent default dragging of selected content
event.preventDefault();
startX = event.screenX - x;
startY = event.screenY - y;
$document.on('mousemove', mousemove);
$document.on('mouseup', mouseup);
});
function mousemove(event) {
if (headerHeight === 0) {
headerHeight = parseInt(header.css('padding-top'), 10) +
parseInt(header.css('padding-bottom'), 10) +
parseInt(header.css('margin-top'), 10) +
parseInt(header.css('margin-bottom'), 10) +
header.height() +
32;
}
y = event.screenY - startY;
x = event.screenX - startX;
// Top
if (topMargin + y < 0) {
y = -topMargin;
}
// Bottom
if (y + headerHeight > $window.innerHeight) {
y = $window.innerHeight - headerHeight;
}
// Left side
if (x < 0) {
x = 0;
}
// Right side
if (x > ($window.innerWidth - draggable.width())) {
x = $window.innerWidth - draggable.width();
}
draggable.css({
top: y + 'px',
left: x + 'px'
});
}
function mouseup() {
$document.unbind('mousemove', mousemove);
$document.unbind('mouseup', mouseup);
}
};
}
}(window.angular));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment