From 667082ffa8c78e3afe5d9e12befaea9a956ee303 Mon Sep 17 00:00:00 2001 From: Justin Gregory Date: Thu, 25 Feb 2016 23:29:40 -0600 Subject: [PATCH] Position drag element relative to mousedown on original draggable element (Issue 34) This only applies to the automatically generated clone element, not custom template elements. Original issue can be found here: https://github.com/One-com/knockout-dragdrop/issues/34 --- lib/knockout.dragdrop.js | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/lib/knockout.dragdrop.js b/lib/knockout.dragdrop.js index 919c8be..c6ac4aa 100644 --- a/lib/knockout.dragdrop.js +++ b/lib/knockout.dragdrop.js @@ -178,19 +178,20 @@ this.dirty = false; }; - function DragElement(element) { + function DragElement(element, eventOffset) { this.element = element; toggleClass(this.element, 'drag-element', true); this.element.style.position = 'fixed'; this.element.style.zIndex = 9998; this.element.addEventListener('selectstart', function () { return false; }, true); + this.eventOffset = eventOffset || { top: 0, left: 0 }; } DragElement.prototype.updatePosition = function (event) { - this.element.style.top = (event.pageY - window.pageYOffset) + 'px'; - this.element.style.left = (event.pageX - window.pageXOffset) + 'px'; - this.element.style.top = (getEventCoord(event, 'pageY') - window.pageYOffset) + 'px'; - this.element.style.left = (getEventCoord(event, 'pageX') - window.pageXOffset) + 'px'; + this.element.style.top = (event.pageY - window.pageYOffset - this.eventOffset.top) + 'px'; + this.element.style.left = (event.pageX - window.pageXOffset - this.eventOffset.left) + 'px'; + this.element.style.top = (getEventCoord(event, 'pageY') - window.pageYOffset - this.eventOffset.top) + 'px'; + this.element.style.left = (getEventCoord(event, 'pageX') - window.pageXOffset - this.eventOffset.left) + 'px'; }; DragElement.prototype.remove = function () { @@ -535,7 +536,13 @@ var dragElement = null; if (typeof options.element === 'undefined') { - dragElement = new DragElement(createCloneProxyElement()); + var bodyRect = document.body.getBoundingClientRect(); + var elemRect = element.getBoundingClientRect(); + var eventOffset = { + top: startEvent.pageY - elemRect.top + bodyRect.top, + left: startEvent.pageX - elemRect.left + bodyRect.left, + }; + dragElement = new DragElement(createCloneProxyElement(), eventOffset); } var overlay = document.createElement('div');