Skip to content Skip to sidebar Skip to footer

How To Get Maximum Document Scrolltop Value

I am making some plugin and I need to get maximum scrollTop value of the document. Maximum scrollTop value is 2001 , but $(document).height() returns 2668 and $('body')[0].scrollHe

Solution 1:

The code in your comments should work:

$(document).height() - $(window).height()

Here's an example that alerts when you scroll to the maximum scroll position: http://jsfiddle.net/DWn7Z/


Solution 2:

Here is an answer i wrote https://stackoverflow.com/a/48246003/7668448, it's about a polyfill for scrollTopMax which is a native property for Element objects. (only mozilla). Look at the response, you can really like it.

Bellow just a quick snippet. The answer in the link is more rich (make sure to look).

(function(elmProto){
    if ('scrollTopMax' in elmProto) {
        return;
    }
    Object.defineProperties(elmProto, {
        'scrollTopMax': {
            get: function scrollTopMax() {
              return this.scrollHeight - this.clientTop;
            }
        },
        'scrollLeftMax': {
            get: function scrollLeftMax() {
              return this.scrollWidth - this.clientLeft;
            }
        }
    });
}
)(Element.prototype);

use example:

var el = document.getElementById('el1');
var max = el.scrollLeftMax; 

Solution 3:

If you want to "guess" the maximum scrolltop value, maybe you should compare the height of the document and the viewport height (size of your window).

/**
 * Return a viewport object (width and height)
 */
function viewport()
{
    var e = window, a = 'inner';
    if (!('innerWidth' in window))
    {
        a = 'client';
        e = document.documentElement || document.body;
    }
    return { width : e[ a+'Width' ] , height : e[ a+'Height' ] }
}

// Retrieve the height of the document, including padding, margin and border
var documentHeight = $(document).outerheight(true);
var viewPortData = viewport();

var maxScrollTop = documentHeight - viewPortData.height;

Of course, in your plugin, you should also add a listener on the resize event, and re-calculate the maximum scrollTop.


Solution 4:

In vanilla Javascript I'm currently doing this:

getScrollTopMax = function () {
  var ref;
  return (ref = document.scrollingElement.scrollTopMax) != null
      ? ref
      : (document.scrollingElement.scrollHeight - document.documentElement.clientHeight);
};

This returns Gecko's non-standard scrollTopMax if it exists, otherwise calculates it. I'm using document.scrollingElement here, which only exists on particular browsers, but it's easy to polyfill.


Solution 5:

Try this, a simple and easy solution :-

document.body.getBoundingClientRect().bottom;

Found this on W3 Schools....


Post a Comment for "How To Get Maximum Document Scrolltop Value"