Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting mouse position while dragging (JS + HTML5)

Tags:

I'm currently implementing a small demo app trying to get my head around drag and drop with HTML5. What I'm trying to do at the moment is getting the position of the cursor when the user is dragging however I'm having some issues.

It seems that the 'mousemove' event doesn't get fired when dragging which is stopping me from figuring out the current position of the mouse. I could use the 'drag' event, however I can't figure out how to get the position from the 'drag' event object.

like image 728
NRaf Avatar asked Apr 27 '11 00:04

NRaf


People also ask

How do I drag and drop with mouse?

For example, to drag-and-drop an object, such as an icon, you first move your mouse cursor over it. Then, press and hold down the left mouse button, move the object to the location you desire, and release the mouse button to set it down.

Can JavaScript Move cursor?

You cannot move the actual mouse pointer in Javascript. You can, however move a pointer shaped image and pretend that you can. :-) Better yet, you can move a cat image around, following the mouse cursor, and try to use it to chase the cursor into the position you want.

How do you drag in JavaScript?

Introduction to JavaScript Drag and Drop API To drag an image, you simply hold the mouse button down and then move it. To drag the text, you need to highlight some text and drag it in the same way as you would drag an image.


1 Answers

//  JavaScript  document.addEventListener("dragover", function(e){     e = e || window.event;     var dragX = e.pageX, dragY = e.pageY;      console.log("X: "+dragX+" Y: "+dragY); }, false);  //  jQuery  $("body").bind("dragover", function(e){     var dragX = e.pageX, dragY = e.pageY;      console.log("X: "+dragX+" Y: "+dragY); }); 

Runnable code snippet below:

//	JavaScript (a really great library that extends jQuery, check it out)    document.addEventListener("dragover", function(e){  e = e || window.event;  var dragX = e.pageX, dragY = e.pageY;    console.log("X: "+dragX+" Y: "+dragY);  }, false);    //	jQuery (the native-language JavaScript is written in)    $("body").bind("dragover", function(e){  var dragX = e.pageX, dragY = e.pageY;    console.log("X: "+dragX+" Y: "+dragY);  });
<!doctype>  <html>    <head><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></head>    <body>LOL drag something over me (open the console)</body>  </html>
like image 55
mattsven Avatar answered Oct 02 '22 16:10

mattsven