javascript use drag to move element

Peri Hartman picture Peri Hartman · Aug 23, 2017 · Viewed 18.2k times · Source

How does one set the position of an element? When the user drags an element (an image), I'd like to have it move synchronously. I see that my "mousemove" handler is being called. However I cannot get the element to actually move.

Here's the mousemove handler (the element being dragged is "overlay"):

function handleMouseMove (event)
{
  var deltaX = event.movementX;
  var deltaY = event.movementY;

  var divOverlay = document.getElementById ("overlay");
  var rect = divOverlay.getBoundingClientRect();

  divOverlay.style.left = rect.x + deltaX;
  divOverlay.style.top = rect.y + deltaY;
}

Here's the html for "overlay":

<div id="overlay">
  ... some other stuff ...
  <img id="large" src="something.jpg" >
</div>

And the css:

#overlay {position:absolute; left:0; top:0}

It appears that the default drag action manifests, which is a shadow of "overlay" that moves with the mouse. But the element itself does not move.

Answer

Ali picture Ali · Aug 23, 2017

Not sure about your actual implementation. However this code works:

To do it using your code, here is the code. One obvious issue with your code is you need to add 'px' to your style.left and style.right. Also it is unknown how you actually handle the event from your code. Using this code, the element moves in a circle, you need to fix it but you get the idea.

var divOverlay = document.getElementById ("overlay");
var isDown = false;
divOverlay.addEventListener('mousedown', function(e) {
    isDown = true;
}, true);

document.addEventListener('mouseup', function() {
  isDown = false;
}, true);

document.addEventListener('mousemove', function(event) {
   event.preventDefault();
   if (isDown) {
   var deltaX = event.movementX;
   var deltaY = event.movementY;
  var rect = divOverlay.getBoundingClientRect();
  divOverlay.style.left = rect.x + deltaX + 'px';
  divOverlay.style.top  = rect.x + deltaX + 'px';
 }
}, true);

Below is another way of doing it. Codepen example

var offset = [0,0];
var divOverlay = document.getElementById ("overlay");
var isDown = false;

divOverlay.addEventListener('mousedown', function(e) {
isDown = true;
offset = [
    divOverlay.offsetLeft - e.clientX,
    divOverlay.offsetTop - e.clientY
 ];
}, true);

document.addEventListener('mouseup', function() {
   isDown = false;
}, true);

document.addEventListener('mousemove', function(e) {
    event.preventDefault();
    if (isDown) {
        divOverlay.style.left = (e.clientX + offset[0]) + 'px';
        divOverlay.style.top  = (e.clientY + offset[1]) + 'px';
   }
}, true);