Mjukis Mjukis - 2 years ago 97
jQuery Question

How to get element position relative to parent?

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




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


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


#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 Source

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


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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download