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].scrollHeight gives me undefined.
How to get 2001 through javascript/jquery?!
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/
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.
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.
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;
来源:https://stackoverflow.com/questions/12965296/how-to-get-maximum-document-scrolltop-value