javascript: difference between scrollTop and offsetTop

dlh picture dlh · Dec 9, 2013 · Viewed 18.6k times · Source

Is there a predictable relationship between cummulative offsetTop of an <a> element and the value of scrollTop after navigating to that <a> element?

I had naively assumed they would be equal, but I've encountered cases where scrollTop is larger (the scroll position is further down the page).

The following defines the question more precisely:

function TotalOffsetTop (e)
{
    var offset = 0;
    do 
        offset += e.offsetTop;
    while (e = e.offsetParent);
    return offset;
}

//navigate to MyBookmark
location.hash = "#MyBookmark"

var BookmarkOffsetTop = TotalOffsetTop(document.getElementByID("MyBookmark"));   
var CurrentPosition = document.getElementsByTagName("body")[0].scrollTop;

if ( CurrentPosition != BookmarkOffsetTop ) alert("Design Flaw!");

My ultimate goal is to find the nearest <a> tag whose start is above the top of the current viewport. This is so I can jump backward (and forward) to bookmarks relative to the current position in a document.

Are there some other measures I should be using instead of scrollTop and cummulative offsetTop?

I'm exploring the problem using Chrome, but I'd like to ultimately find something that works in at least several modern browsers. I'm trying to avoid jQuery.

Answer

EvilBeer picture EvilBeer · Dec 10, 2013

The main difference without getting into too much detail:

offsetTop is read-only, while scrollTop is read/write. According to this, you'd be on the safer side if you were to use offsetTop:

Be careful about the scrollTop property of the html element!

In Internet Explorer earlier than version 8, it retrieves the scroll amount in physical pixel size, while from version 8, it returns the amount in logical pixel size. What does it mean? If the browser is not at the normal zoom level (the user has the ability to zoom in or out a web page: CTRL and +, CTRL and -), the scrollTop property works differently from version 8 than in earlier versions.

The scroll amount is calculated in the default pixel size in Internet Explorer before version 8 even if the current pixel size in the document is different. From Internet Explorer 8 and in Firefox, Opera, Google Chrome and Safari, the scroll amount is calculated in the current pixel size.

For example, if the zoom level is 200%, the scrollTop property retrieves two times greater values before version 8 than from version 8 for the same scroll position.

Source for the text and more info on the two: Source