views:

201

answers:

2

Hi, I have the following markup:

<div id="selectable1">
<span class="drag">Some Text</span>
<span class="drag">Some Text</span>
<span class="drag">Some Text and <span class="drag">Some Other Text</span></span>
</div>

I need to create a function that will get the relative position of any span (nested or not) to the main parent - #selectable1.

I have tried to use position() but my code does not work:

$(".drag").live('click',function(){ 
var relativepos = $('.drag').position().left
alert(relativepos); 
});

Any tips? Thanx

+2  A: 

Within the event, you refer to the current element as this, and not by the generic classname. Remember, the class .drag refers to many elements while this refers to the current element.

$(".drag").live('click',function(){ 
  alert( $(this).position().left ); 
});
Jonathan Sampson
Thanx but unfortunately I can not get the position relative to my #selectable1 div. I get position relative to document body.
Mircea
Set `#selectable1 { position:relative }`.
Jonathan Sampson
Online demo: http://jsbin.com/umozo/2/edit
Jonathan Sampson
Yeap! It works. Thanx a lot!
Mircea
Isn't possible to make the nested span to get also the relative position regarding #selectable1?- it seems that in your demo it works but I am having problems with my code
Mircea
A: 

Thanks Man, it worked, I had been in a lot strees before due to position:relative thing.. cheers..

Bikash