John
John

Reputation:

Is it possible to find distance from bottom to current scroll state in jquery

Suppose have scrolled down to the middle of a web page.

Is it possible to find the distance, in length or pixels, from the bottom?

Like when scroll-bar hits the bottom then its 0 but if it 500px from the bottom then I need that 500px value.

Upvotes: 17

Views: 19529

Answers (6)

Crozin
Crozin

Reputation: 44386

For the whole page:

let scrollPosition = window.pageYOffset;
let windowSize     = window.innerHeight;
let bodyHeight     = document.body.offsetHeight;

alert(Math.max(bodyHeight - (scrollPosition + windowSize), 0));

For a specific element:

let scrollDistanceTotal      = el.scrollHeight - el.clientHeight;
let scrollDistanceFromBottom = scrollDistanceTotal - el.scrollTop;

Upvotes: 19

schmerb
schmerb

Reputation: 314

I had to further tweak previous answers to make it work:

distFromBottom = $(document).height() - $(window).scrollTop() - $(window).height();

Just to break it down:

let bottomToWinTop = $(document).height() - $(window).scrollTop();

This gets the distance from the bottom of document to the top of the window. Since window height will vary, subtract the current window height to get the offset from the bottom

let bottomToWinBottom = bottomToWinTop - $(window).height();

Now bottomToWinBottom = distFromBottom = 0 when user is scrolled completely down the page and as they scroll up, it's value is the distance below the window which makes for a good indicator of vertical positioning.

Upvotes: 0

Annarfych
Annarfych

Reputation: 537

Here is the code in vanilla JS:

var distanceFromBottom = document.body.scrollHeight - window.innerHeight - window.scrollY

Upvotes: 2

Simon Sawyer
Simon Sawyer

Reputation: 327

Tweaking rkleine's answer. I found it was actually, this:

$(document).height() - ($(window).height() + $('body').scrollTop())

i.e. $(window) for the height not $('body')

Upvotes: 3

James
James

Reputation: 21

var distanceFromBottom = $(document).height() - $(window).height() - $(document).scrollTop();

Upvotes: 0

rkleine15
rkleine15

Reputation: 147

Also try this:

$(document).height() - ($('body').height() + $('body').scrollTop())

Upvotes: 5

Related Questions