6

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

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
3gwebtrain
  • 14,640
  • 25
  • 121
  • 247

3 Answers3

4

Set the position property of the p tag to relative:

p {
  color: green;
  position: relative;
}

http://jsfiddle.net/zPdxB/

Ram
  • 143,282
  • 16
  • 168
  • 197
2

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.

Community
  • 1
  • 1
Levi
  • 2,103
  • 14
  • 9
1

from the docs

The .position() method allows us to retrieve the current position of an element relative to the offset parent.

Contrast this with .offset(), which retrieves the current position relative to the document.

When positioning a new element near another one and within the same containing DOM element, .position() is the more useful.

If we talk about your scenario then :

Currrently both .position() and .offset() have same parent and they will get the offset position of the document.

Now if you add one more attribute in the css class of <p> position:relative; you can find the difference then.

In short:

.offset().top will get the top from the document.

.position().top will get the top from the relative parent.(if parent is relatively set)

you can find the difference here: http://jsfiddle.net/BhsrS/1/

checkout the fiddle: http://jsfiddle.net/BhsrS/1/

Jai
  • 74,255
  • 12
  • 74
  • 103