Skip to content Skip to sidebar Skip to footer

Get Percentage Of Scroll Position

The problem: What would be the mathematical formula to calculate (regardless of the scrollHeight of the document) how far the bottom of the scrollbar is from it's total bottom (whi

Solution 1:

Returns a number between 0 to 100 relative to scroll position:

document.onscroll = function(){ 
  var pos = getVerticalScrollPercentage(document.body)
  document.body.innerHTML = "<span>" + Math.round(pos) + "%<span>"
}

functiongetVerticalScrollPercentage( elm ){
  var p = elm.parentNodereturn (elm.scrollTop || p.scrollTop) / (p.scrollHeight - p.clientHeight ) * 100
}
body{ height:2000px }
span{ position:fixed; font:5em Arial; color:salmon; }

Difference between scrollHeight & clientHeight

Solution 2:

When you scroll to the bottom, the final position value is equal to the height of your document minus the height of one screen (viewport). So if you compute:

scrollPositionRelative = scrollPosition / (documentHeight - viewportHeight);

The values will be in the range 0-1 as expected.

Here's the function used in the example given at the end.

functiongetScrollPosition () {
  var viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); // Viewport height (px)var scrollPosition = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; // Current scroll position (px)var documentHeight = $(document).height(); // Document height (px)var scrollPositionRelative = scrollPosition / (documentHeight - viewportHeight); // The document height is reduced by the height of the viewport so that we reach 100% at the bottomreturn {
    documentHeight: documentHeight,
    relative: scrollPositionRelative,
    absolute: scrollPositionRelative * documentHeight // Yields an "average" pixel position
  };
}

See it in action: http://jsbin.com/tawana/1/

Post a Comment for "Get Percentage Of Scroll Position"