JQuery draggable - how to access coordinates

How can you access the dynamically changing coordinates of a dragged object? I do not need coordinates in stop , but a constant stream of location information.

In other words, if I drag object A around, I should be able to move object B parallel in parallel (1), observing the changes in object A , and then (2) applying them to the position of object B

In this code, I want the red block ( obj2 ) to move with the blue ( obj1 ).

 <html> <head> <style> #obj1 { position:fixed; top:50px; left:50px; width: 40px; height: 40px; background-color: blue; } #obj2 { position:fixed; top:150px; left:150px; width: 40px; height: 40px; background-color: red; } </style> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $('#obj1').draggable(); }) </script> </head> <body> <div id="obj1"></div> <div id="obj2"></div> </body> </html> 
+4
source share
3 answers

You can use drag event to drag and drop:

 $("#obj1").draggable({ drag: function(event, ui) { var pos = ui.position; $("#obj2").css({ left: pos.left + 100, top: pos.top + 100 }); } });​ 

DEMO: http://jsfiddle.net/kPEfL/

+3
source

A drag and drop plugin has 3 events: start, drag and stop (all of which provide coordinates). You can bind a drag event and get the information you need in your callback.

Here you can find an example and a demo.

+1
source

The properties of the offsetY and offsetY events are suitable for this purpose; you can attach a drag handler to receive them:

 $('#obj1').bind('drag', function(event) { console.log(event.offsetY); // dymamic y position console.log(event.offsetX); // dymamic x position }); 

Link:

+1
source

All Articles