I know there're example of doing this on the web but every example is different and so is my own implementation. I'm trying to figure what's wrong with my implementation since it doesn't work as expected.
code snippet:
var mousePressX = -1;
var mousePressY = -1;
document.getElementById("contextMenu").addEventListener("mousedown", function(event) {
mousePressX = event.clientX;
mousePressY = event.clientY;
}, false);
document.getElementById("contextMenu").addEventListener("mouseup", function(event) {
mousePressX = -1;
mousePressY = -1;
}, false);
document.getElementById("contextMenu").addEventListener("mousemove", function(event) {
if (mousePressX != -1 && mousePressY != -1) {
repositionElement(event.target, event.clientX, event.clientY);
}
}, false);
function repositionElement(element, currentMouseX, currentMouseY) {
element.style.left = element.offsetLeft + (currentMouseX - mousePressX) + 'px';
element.style.top = element.offsetTop + (currentMouseY - mousePressY) + 'px';
}
jsfiddle : http://jsfiddle.net/4rLctko8/
can't really figure out what's wrong but I've noticed that if I change the following lines:
element.style.left = element.offsetLeft + (currentMouseX - mousePressX) + 'px';
element.style.top = element.offsetTop + (currentMouseY - mousePressY) + 'px';
to :
element.style.left = currentMouseX - mousePressX + 'px';
element.style.top = currentMouseY - mousePressY + 'px';
The element will be properly dragged only when it's being dragged towards the positive x-axis (to the right) and towards the positive y-axis (to the bottom) and when mouseup is triggered it'll be positioned in somewhere near the left-most top-most corner area (around 0,0)