Reputation: 2199
I want to get the position of an element relative to its parent element. So for this i am using jquery position function
I created a JsFiddle.
In this fiddle i am accessing the top & left
position of #child
element. It should return top : 0 and left : 0
because it is the children of #p
element and its position is relative but it is returning top : 223px and left : 1px
. Can anyone please help me ?
Upvotes: 2
Views: 393
Reputation: 1298
Perhaps something like this :
function relative_pos(node) {
var parentOf = $(node).parent().offset();
var child = $(node).offset();
return {top: child.top - parentOf.top, left: child.left - parentOf.left};
}
console.log(relative_pos("#child"));
Upvotes: 0
Reputation: 178
here is the tweak The problem was you did not specify the parent's position as relative. So the child position was calculated with respect to body
<style type="text/css">
#gp {
width: 500px;
height: 200px;
margin: 0;
border: 1px solid black;
background-color:gray;
overflow:hidden;
}
#p {
width: 600px;
height: auto;
float: left;
position: relative;
}
#child{
position: relative;
}
</style>
<div id="gp">
<div id="p">
<div id="child">
</div>
</div>
</div>
jQuery(document).ready(function(){
alert($("#child").position().top + " " + $("#child").position().left);
});
Upvotes: 2