Javascript – How to get the position of a clicked element

javascriptjquery

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!

Best Solution

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/