How to Drag an image without jQuery [duplicate]

3

I would like to make the user be able to drag the image when clicking on it, however without using jquery for this, using pure JavaScript. I can get the mouse position on the screen, but I can not do the function for the image to be dragged. Could you help me?

Here's my fiddle:

link

    
asked by anonymous 26.05.2015 / 03:18

1 answer

2

I made a simple implementation using the mouse* events to detect the click, drag and drop of the image. In this last event, the position of the image is updated with the mouse position. It can improve, but it's a start. Tested on Chrome and Firefox.

var img = document.querySelector("#img");
img.ondragstart = function() { return false; };

function dropImage(e) {
  img.style.top = e.clientY + 'px';
  img.style.left = e.clientX + 'px';
}

function drop(e) {
  dropImage(e);
  document.removeEventListener("mousemove", dropImage);
  document.removeEventListener("mouseup", drop);
}

img.addEventListener("mousedown", function(){
  document.addEventListener("mousemove", dropImage);
  document.addEventListener("mouseup", drop);
});
#img {
  width: 25%;
  position: absolute;
}

#img:hover {
  cursor: -webkit-grab;
  cursor: grab;
}
<img src="http://gabrielozzy.com/site-amor/img/slide_1.jpg"id="img" />
    
26.05.2015 / 15:40