javascript use drag to move element

javascript drag and drop example
jquery draggable
mouse drag event javascript
drag and drop javascript demo
draggable js
draggable div html5
html5 drag and drop multiple elements
javascript drag and drop list

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.

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);

How To Create a Draggable HTML Element, Learn how to create a draggable HTML element with JavaScript and CSS. Draggable DIV Element. Click here to move. Move. this. DIV� At each point during the move, our draggable element tracks and moves precisely with our pointer's position: Once we move the pointer to the final destination, we release the press: When the press is released, our draggable element stops tracking the pointer and remains put at the final destination. The drag is complete. Code, Please!

Here is an example for drag item . For css, we need position: absolute For js, remove onmouseup and onmousemove event after finish drag

<!DOCTYPE html>
<html>
<head>
  <style type="text/css">
    .AB {
      background: red;
      position: absolute;
      width: 100px;
      height: 100px;
    }
  </style>
</head>

<body>
  <div id="A" class="AB"></div>

  <script type="text/javascript">
    var divA = document.getElementById("A");

    divA.addEventListener('mousedown', function() {
      startDrag();
    });

    function startDrag() {
      document.onmouseup = finishDrag;

      document.onmousemove = function(e) {
        divA.style.top = (divA.offsetTop + e.movementY) + "px";
        divA.style.left = (divA.offsetLeft + e.movementX) + "px";
      }
    }

    function finishDrag() {
      document.onmouseup = null;
      document.onmousemove = null;
    }
  </script>
</body>
</html>

Create a Draggable Element in JavaScript, Learn how to easily drag an element around using either the mouse or the element with our pointer, we move our pointer to a new position:. To drag the element we can use position:fixed, it makes coordinates easier to manage. At the end we should switch it back to position:absolute to lay the element into the document. When coordinates are at window top/bottom, we use window.scrollTo to scroll it. More details in the code, in comments.

Is jQuery an option for you? It makes what you are doing really simple since the code already exists.

http://jqueryui.com/demos/draggable/

Demo : http://jsfiddle.net/wfbY8/4/

JavaScript Code

window.onload = addListeners;

function addListeners(){
    document.getElementById('dxy').addEventListener('mousedown', mouseDown, false);
    window.addEventListener('mouseup', mouseUp, false);

}

function mouseUp()
{
    window.removeEventListener('mousemove', divMove, true);
}

function mouseDown(e){
  window.addEventListener('mousemove', divMove, true);
}

function divMove(e){
    var div = document.getElementById('dxy');
  div.style.position = 'absolute';
  div.style.top = e.clientY + 'px';
  div.style.left = e.clientX + 'px';
}​

Drag'n'Drop with mouse events, In the modern HTML standard there's a section about Drag and Drop with We can use that code to check what element we're “flying over” at� The event occurs when the dragged element leaves the drop target: ondragover: The event occurs when the dragged element is over the drop target: ondragstart: The event occurs when the user starts to drag an element: ondrop: The event occurs when the dragged element is dropped on the drop target

I did make something similar few weeks ago for Angular, see here. It might help you a bit.

Basically, I wanted to do something you're probably thinking of doing, but to use drag events you also need to drop the elements you're dragging (at least that's what I ended up searching). So if you just want to drag/move the elements you need to be able to set their position on the page using top, bottom and left, right styles. So you those elements must have the position fixed or absolute ideally.

Then you go for the core of this, which is to calculate vector your going to move the element with. Because mousemove event only dispatches the MouseEvent which get you an access to mouse coordinates, you can count up in what vector your mouse has moved and move the element by the same vector.

Basically what I did was (hope it's understandable in ES5):

var elementPosition = [0,0];
var mousePosition   = [0,0];
var element         = document.getElementById('yourElement');

var mainEH = function (event) {
    mousePosition = [event.clientX, event.clientY];
    document.addEventListener('mousemove', calcEH);
    document.addEventListener('mouseup', removeHandlers);
    document.addEventListener('contextmenu', removeHandlers);
};

var calcEH = function (event) {
    var vector      = [-mousePosition[0] + event.clientX, -mousePosition[1] + event.clientY];
    mousePosition   = [mousePosition[0] + vector[0], mousePosition[1] + vector[1]];
    elementPosition = [elementPosition[0] + vector[0], elementPosition[1] + vector[1]];
    updatePosition();
};

var removeHandlers = function () {
    document.removeEventListener('mousemove', calcEH);
    document.removeEventListener('mouseup', removeHandlers);
    document.removeEventListener('contextmenu', removeHandlers);
};

function updatePosition() {
    element.style.left = elementPosition[0] + "px";
    element.style.top  = elementPosition[1] + "px";
}

element.addEventListener('mousedown', mainEH, true);

I'm not sure if this exact code is working as I cannot test it now, but you can see here how I did this using angular. Hope it'll work just fine for you. At least you get the idea. Anyway, you might need to run some function that sets up initial position of the element for you.

UPDATE

I've just realized that it's not exactly what you're looking for. If I understood you correctly you want to move the whole element while dragging and dropping. However I will probably leave the answer here because the solution might be pretty much similar. I would probably do it by using the logic I posted before and to actually be able to move the element I would set it's position to absolute while mousemove event is fired, then on mouseup you can remove position absolute attribute.

Drag and Drop Elements with Vanilla JavaScript and HTML , Here's how to build JavaScript functions that utilize the native HTML Drag and Drop API. Now if you try to move the draggable element with your mouse (sorry mobile visitors! 🙈) you should see a lighter version of the element move with your cursor on drag. Without setting this draggable attribute to true, the default value is auto. This means whether the element is draggable will be determined by your browser’s default setting.

HTML Drag and Drop API, HTML Drag and Drop interfaces enable applications to use drag-and-drop features in browsers. The user may select draggable elements with� The drag event is fired every few hundred milliseconds as an element or text selection is being dragged by the user.

Draggable, Allow elements to be moved using the mouse. Move the draggable object by clicking on it with the mouse and dragging it anywhere within the viewport. You can also use this method to move an element from one element to another. Tip: Use the insertBefore() method to insert a new child node before a specified, existing, child node. So you can do that to do the job, this is what I created for you, using appendChild(), run and see how it works for your case:

Drag and drop element in a list, Manage HTML DOM with vanilla JavaScript. Drag and drop element in a list By using the similar approach mentioned in the Make a draggable element post� I modified Shaedo's code a little bit, wraps it in a function and add a feature that you can drag an element by only parts of it or its children, say the title bar of a div. Note in this demo, you can only drag the red area to move the blue area.

Comments
  • It seems that the problem was solved in jquery.sortable. Just look how it works.
  • Well, I'd appreciate an actual answer, if you are able. I looked at sortable but don't see anything that looks like assigning an element position - though I realize it must be infered someplace. Apologies, I'm not very familar with jquery.
  • for some reasons I don't consider SO as a code generator service.
  • Thanks. Adding 'px' made the difference. My code still doesn't work properly but at least the element now moves. I now realize that when updating or reading the DOM style fields, they should have the exact syntax defined as used in CSS. This is all new for me.
  • Can we add limit to 'px' that it should go higher than 500px or something from top and bottom when dragging?
  • I don't see anything significantly different in what you posted versus my code. You, also, assign to div.style.top and div.style.left. Everything else is the same except for usig e.clientX instead of getBoundClientRect(). I doubt that is significant regarding the problem I'm encountering.
  • find many problem for example div.style.position and function mouseUp() and function mouseDown(e) , I will update the Jsfile to show the Demo Here jsfiddle.net/g6m5t8co/658