How to get x and y position from jQuery ui draggable?

Here is an example http://jsfiddle.net/naqbq/

How to capture the current position for x and y after repositioning the image?

 <input type="hidden" name="source_x" id="source_x" /> <input type="hidden" name="source_y" id="source_y" /> 
+4
source share
4 answers

In the stop callback, you can use ui.helper to access the item being dragged. Then use offset on it, as Brad suggested:

 $("#image").draggable({ stop:function(event,ui) { var wrapper = $("#wrapper").offset(); var borderLeft = parseInt($("#wrapper").css("border-left-width"),10); var borderTop = parseInt($("#wrapper").css("border-top-width"),10); var pos = ui.helper.offset(); $("#source_x").val(pos.left - wrapper.left - borderLeft); $("#source_y").val(pos.top - wrapper.top - borderTop); alert($("#source_x").val() + "," + $("#source_y").val()); } });​ 

Then you just need to configure it for your packaging - subtract its offset and the width of its border - and set it to your input val . (sorry for hard coding the border, but I could not extract it using css ) (Edit: there he found a solution in another question )

http://jsfiddle.net/mgibsonbr/naqbq/4/

+10
source

You can use jQuery .offset() .

http://api.jquery.com/offset/

 alert($('#image').offset().top); alert($('#image').offset().left); 
+5
source

You should use the inline stop event:

 $("#image").draggable({ stop: function() { // check for positioning here using .css or .offset } }); 
+2
source

You can get the top and the lion:

 $('selector').draggable({ drag: function(event, ui) { ui.position.top; // .left // or $('selector').position().top; // current position of an element relative to the offset parent $('selector').offset(); // retrieves the current position relative to the document. } }) 
+2
source

Source: https://habr.com/ru/post/911667/


All Articles