Mjukis Mjukis - 6 months ago 17
jQuery Question

How to get element position relative to parent?

How can i change, so that y is set to zero?


FIDDLE

http://jsfiddle.net/DGbT3/2672/

HTML

<div id="parent" style="width: 300px; height: 300px; border: 1px solid black; margin-top: 50px;">
<div id="dragThis">
<ul>
<li id="posX"></li>
<li id="posY"></li>
</ul>
</div>
</div>


JS

$('#dragThis').draggable({
drag: function() {
var position = $(this).position();
var xPos = position.left;
var yPos = position.top;
$('#posX').text('x: ' + xPos);
$('#posY').text('y: ' + yPos);
}
});


CSS

#dragThis {
width: 6em;
height: 6em;
padding: 0.5em;
border: 3px solid #ccc;
border-radius: 0 1em 1em 1em;
position: relative;
top: 0px;
}


I've been changing "position" to "offset" and i have tried to change the CSS position. But i cannot figure out, how to get y, to count top from its parent.

Answer

Take the x and y position of its container and deduct those values from the appropriate values.

jsFiddle.

Alternatively, give the draggable element's position: absolute and the parent position: relative.

jsFiddle.

Comments