Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why i am getting same value in offset and position in jQuery?

Tags:

jquery

I have placed a span inside of the paragraph tag, now the position top should show as 0 and the offset should show some other value (need to calculate from document), but i am getting the same value in both...

i am wrong?

this is my code:

HTML:

<div></div>
<p>paragraph<span>span</span>paragraph</p>

Jquery:

$('span').click(function(){
console.log($(this).position().top,$(this).offset().top)
})

CSS:

p{
  color:green;
}

span{
  color:red;
}

div{
  height:100px;
  border:2px solid blue;
}

jsfiddle here

like image 961
3gwebtrain Avatar asked Jan 11 '13 07:01

3gwebtrain


2 Answers

Set the position property of the p tag to relative:

p {
  color: green;
  position: relative;
}

http://jsfiddle.net/zPdxB/

like image 62
undefined Avatar answered Sep 21 '22 05:09

undefined


jQuery: Difference between position() and offset()

Position referes to the position relative to the offset parent which is actually the document in your example, because the p is not a positioned element, but rather inline. That is why you are getting the same values back.

if you make your p element have absolute or relative positioning, the position of the span will now be relative to the P element as you originally expected, and therefore a different value from offset.

like image 37
Levi Avatar answered Sep 17 '22 05:09

Levi