Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the position of a clicked element

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!

like image 534
Imesh Chandrasiri Avatar asked May 31 '13 08:05

Imesh Chandrasiri


1 Answers

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/

like image 65
CodingIntrigue Avatar answered Oct 09 '22 09:10

CodingIntrigue