Nate Rubin
Nate Rubin

Reputation: 832

Should offset().top ever change

I'm pretty new to jQuery and am trying to do something with scrolling. Through my research I've come across scrollTop() and offset() as tools to use for this. I was running a test where pushing a button would alert the value of offset().top of a div. When I scroll a little bit and press the button, that value changes. I was under the impression that this value should remain the same since it's the distance from the div to the top of the document doesn't change when I scroll. Could someone explain why this is happening?

Upvotes: 0

Views: 6170

Answers (2)

iConnor
iConnor

Reputation: 20189

Element.offset().top; is the amount of pixels from the top of the document the element is, so if you do this

alert( $('#element').offset().top );

$('#element').css('margin-top', '50px');

alert( $('#element').offset().top );

You should see a change in values

Whereas scrollTop(); is for scrollable elements so it will detect how far down the scroller is This will only work with the html or body unless your element has overflow:scroll

so

alert( $('#element').scrollTop() );
// Scroll the Element within 5 seconds

window.setTimeout(function(){ 
    alert( $('#element').scrollTop() );
}, 5000);

Cut a long story short and you could say

offset with change when the element is moved and scrollTop will change when the element is scrolled

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074168

If the element you're measuring is in a scrollable container, then yes, top can change, because the scrolling of the container is considered. top will be the visual distance from the top of the document to the element. If the element has a container that's scrolled, and you change that scrolling, that distance changes.

Consider:

<div style="height: 300px; overflow: scroll">
  <p>x</p>
  <!-- lots and lots more of those -->
  <p id="target">click me</p>
</div>

If you scroll the containing div, the visual distance from the top of the document to the top of #target changes.

Live Example | Live Source

Upvotes: 2

Related Questions