JQuery - get relative position and attribute of dropped elements

I have drag-and-drop items that can be dropped in areas of dropped areas. If an element is discarded, the drop function is called:

 $('#droppable').droppable({ scope: "items", drop: function (event, ui) { // this one is called if an element is dropped in this droppable area } }); 

My draggable item:

 <div class="drag" data-noteid="10">Drag me</div> ... $('.drag').draggable({ revert: "invalid", scope: "items" }); 

What I need to know if the item is reset is the data-noteid and the relative position of the droppable area. So, if the element is omitted in the upper left corner, the x / y coordinates should be 0/0.

I created a complete working example here: http://jsbin.com/utivo5/2/

So usually I can access the following attributes:

 alert($(this).data("noteid")); alert($(this).position().top); alert($(this).position().left); 

but all i get in this case is undefined .

Does anyone know how I can access them? I think this is possible with event or ui , which is the parameter of the called drop function ?!

Thanks in advance and best regards, Tim.

+4
source share
2 answers

In this case, you want the ui argument to get draggable, not this , which belongs to the droppable realm, specifically ui.draggable here. It should look like this:

 drop: function (event, ui) { var pos = ui.draggable.offset(), dPos = $(this).offset(); alert("nodeid: " + ui.draggable.data("noteid") + ", Top: " + (pos.top - dPos.top) + ", Left: " + (pos.left - dPos.left)); } 

For the position, we need to subtract the top / left droppable position to get the value you want here to remove the dPos above.

You can test your demo with the above changes .

+15
source

I found for my circumstances that the above did not work. I don’t know why - he always gave me X = -7 and Y = 229.

But this worked (found in the drop function handler):

 alert('X pos in drop parent container = ' + (ui.position.top - $(this).offset().top)); 
+4
source

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


All Articles