How to Drag an Image without jQuery

Asked

Viewed 151 times

3

I would like to make the user be able to drag the image when clicking on it, but without using jquery for that, using pure Javascript. I can pick up the mouse position on the screen, but I’m not able to do the function for the image to be dragged. Could you help me ?

Here is my fiddle:

http://jsfiddle.net/r4sj5218/

  • What would be the problem with using jquery?

  • I would like to improve my knowledge in javascript, and the framework does not enrich so much knowledge... I didn’t want to wear something I don’t know how to do, you know?

  • 1

    I understand perfectly! I think every good developer has thought so one day! But, I think today it is almost impossible to use javascript without using jquery. I think your attitude is very cool, but trying to reinvent the wheel can delay your process a little.

  • I understand, actually I agree, I had to use it in a project and used jQuery, now I decided to do the tests only in Javascript because now that I’ve finished I am "in no hurry", so to speak. By pure learning even!

  • @Michelsimões almost impossible to use javascript without using jquery, disagreeing; try to reinvent the wheel, it may delay your process a little. agree, in terms :)

1 answer

2


I made a simple implementation using the events mouse*, to detect click, drag and when you release the image. In this last event, the position image is updated with the position of the mouse. It can be improved, but it’s a start. Tested in 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" />

  • Excellent answer ! Thank you !

  • I only had one question. Because the Return false in img.ondragstart ?

  • Not to perform the default dragging of the browser. I was having a strange behavior in Firefox

  • Understood, thank you !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.