I'm creating a <table> element in the DOM and using javascript to dynamically append many cells to it. For the sake of explanation let's say I create 10 rows with 10 fields per row. I'm using simple counters to assign unique IDs for the div containers inside of those fields. Easy enough. This is what I get:

<table> <tr><td><div id="field0"><div id="handle0"></div></div></td></tr> ..... <tr><td><div id="field99></div id="handle99"></div></div></td></tr> </table>

Note that the numbers 0-99 are what is dynamically appended to each element ID. I now want to go ahead and attach the jQueryUI .draggable function to each handle and retrieve the coordinates of each handle relative to each surrounding parent div like so:

for (var counter = 0; counter < 100; counter++) { var dragHandle = $('#handle' + counter); var dragField = $('#field' + counter); dragHandle.draggable({ containment: dragField, scroll: false, drag: function () { var offset = $(this).offset(); var xPos = (offset.left) - $(this).offsetParent().offset().left; var yPos = (offset.top) - $(this).offsetParent().offset().top; console.log(xPos); console.log(yPos); // These add up?! } }); }

Now, the functions work, the table gets properly initialized and all of the individual handles in the table are now draggable.

The problem is that the xPos and yPos values that are returned by the above function are not the correct coordinates relative to each field but instead they add up.

I feel like I'm missing something terribly obvious and would really appreciate if someone could help.

Edit: The example above uses console.log for simplification. My original script performs more complex computations in the on drag event. I won't be able to use a class selector to go through all of the elements like someone suggested in the comments because I need to retrieve unique offset and position values for each unique handle ID relative to its unique containment ID.