Reputation: 5679
I've got a parent div in my dom hierarchy and around 100 sub elements inside the parent div. I've binded a click event on each sub element. what I want is the position of sub element from the top of the parent element. I used jquery .position
nd .offset
but both return the position from the top of the page. The parent div is scrollable which means the offlow is hidden. so subtracting top position from the position of the clicked element is not going to work! Can anyone suggest me a work around for this!
Upvotes: 10
Views: 19993
Reputation: 119847
.offset()
returns the position relative to the document, while .position()
returns the position relative to the offset parent. .position()
would be what you want here, but you need the parent to be "positioned" (having a position
other than static
, like relative
, fixed
or absolute
). Otherwise, the nearest positioned parent would be the document itself and .position()
will act like .offset()
Add position:relative
to the parent you want to base the position of your element.
Upvotes: 3
Reputation: 78535
Add a position: relative;
style to the parent element:
HTML:
<div style="position: relative">
<div style="position: absolute; top: 200px; left: 200px;" id="clicker">Click Me</div>
</div>
Javascript:
$(function() {
$("#clicker").click(function() {
var $clicker = $(this);
var pos = $clicker.position();
console.log(pos.top);
console.log(pos.left);
});
});
Upvotes: 6