Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: difference between scrollTop and offsetTop

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.

like image 587
dlh Avatar asked Dec 09 '13 22:12

dlh


1 Answers

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

like image 145
EvilBeer Avatar answered Sep 24 '22 15:09

EvilBeer