10

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!

2
  • Set relative to the parent block and use .position().
    – VisioN
    Commented May 31, 2013 at 8:40
  • you want exact pixel positions or just the base positions ?
    – exexzian
    Commented May 31, 2013 at 8:48

2 Answers 2

6

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);
    });
});

http://jsfiddle.net/LaEsw/

3
  • @DimalChandrasiri it would be better if you posted sample HTML.
    – Joseph
    Commented May 31, 2013 at 8:43
  • @DimalChandrasiri I added an example fiddle Commented May 31, 2013 at 8:44
  • This works! sorry I said it didn't work earlier. I used offset and checked first. Then I tried position and it worked! Thank you! :) Commented May 31, 2013 at 8:48
3

.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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.