So, what it does: You can successfully drag something anywhere, but when you click it again, it resets to its original position (I don’t know why), and when you try to drag it again, as soon as your cursor touches the object it disappears (I don’t know why). I’m hoping someone can tell me why it is happening and how to fix it!
// JavaScript Document
var posX;
var posY;
var element;
function drag() {
element = document.getElementById("square");
posX = event.clientX;
posY = event.clientY;
element.addEventListener("mousemove", move, false);
}
function move() {
element.addEventListener("mouseup", drop, false);
element.style.left = event.clientX - posX + "px";
element.style.top = event.clientY - posY + "px";
}
function drop() {
element.removeEventListener("mousemove", move, false);
element.removeEventListener("mouseup", drop, false);
}
the html is a simple (position is set to relative):
<p id="square" onmousedown="drag(event)">meep</p>
Lastly, and most importantly, thank you all for your time =]
The problem is these values are always set to the offset of the click from the top of the body, NOT from the top of the square element. The first time they worked fine, because the offset from the top of the body was the same thing as that of the element, because its position was right up against the body. Once you moved it, it would have the offset from the side of the body from wherever you just moved it to. When you dragged it with the mouse, it would move it with the mouse’s position shifted over the number of pixels you just moved it to. This often moved it completely off the screen. You want the element to move with the mouse where the top of the element stays in the same position relative to the mouse.
If this doesn’t make sense, post a comment and I’ll try to make it a little clearer. 😀
This worked for me: