Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>posX = event.clientX; posY = event.clientY; </code></pre> <p>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 <em>shifted over the number of pixels you just moved it to.</em> 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. </p> <p>If this doesn't make sense, post a comment and I'll try to make it a little clearer. :D</p> <p>This worked for me:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; // JavaScript Document var posX; var posY; var element; function drag(event) { //added event parameter element = document.getElementById("square"); posX = event.clientX - parseInt( element.offsetLeft ); //this is the big change! posY = event.clientY - parseInt( element.offsetTop ); element.addEventListener("mousemove", move, false); } function move(event) { //added event parameter if (typeof(document.getElementById("square").mouseup) == "undefined") { //this just prevents redundantly adding the same event handler repeatedly, even though duplicates are removed anyway 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); } &lt;/script&gt; &lt;style type="text/css"&gt; body { width: 1000px; height: 1000px; background-color: blue; } p { position: relative; background-color: red; width: 100px; height: 100px; left: 1px; top: 1px; } &lt;/style&gt; &lt;body&gt; &lt;p id="square" onmousedown="drag(event)"&gt;meep&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload