Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 471
Björn C Avatar asked Oct 21 '25 15:10

Björn C


1 Answers

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.

like image 176
alex Avatar answered Oct 23 '25 07:10

alex