ChatGPT解决这个技术问题 Extra ChatGPT

How to detect if browser window is scrolled to bottom?

I need to detect if a user is scrolled to the bottom of a page. If they are at the bottom of the page, when I add new content to the bottom, I will automatically scroll them to the new bottom. If they are not at the bottom, they are reading previous content higher on the page, so I don't want to auto-scroll them since they want to stay where they are.

How can I detect if a user is scrolled to the bottom of the page or if they have scrolled higher on the page?

This one is worked in Angular 6 --> stackoverflow.com/a/42547136/621951

m
mVChr
window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
        // you're at the bottom of the page
    }
};

See demo


Does not work when html/body elements are set to 100% (so that the body fills the entire viewport height)
Use document.documentElement.scrollTop instead of window.scrollY for IE. Not sure which, if any, versions of IE support window.scrollY.
Does not work in Chromium Version 47.0.2526.73 Built on Ubuntu 14.04, running on elementary OS 0.3.2 (64-bit)
I used document.body.scrollHeight instead of offsetHeight (in my case, offsetHeight was always smaller that the window.innerHeight)
@KarlMorrison can you try the bounty-awarded answer (by @Dekel) with your browser?
C
Community

Updated code for all major browsers support (include IE10 & IE11)

window.onscroll = function(ev) {
    if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
        alert("you're at the bottom of the page");
    }
};

The problem with the current accepted answer is that window.scrollY is not available in IE.

Here is a quote from mdn regarding scrollY:

For cross-browser compatibility, use window.pageYOffset instead of window.scrollY.

And a working snippet:

window.onscroll = function(ev) { if ((window.innerHeight + window.pageYOffset ) >= document.body.offsetHeight) { alert("you're at the bottom of the page"); } };



























































































Note for mac

Based on @Raphaël's comment, there was a problem in mac due to a small offset. The following updated condition works:

(window.innerHeight + window.pageYOffset) >= document.body.offsetHeight - 2

I didn't have the chance to test it further, if someone can comment about this specific issue it will be great.


Strange as it may sound, only in my browser I am short of 1 px, and hence the condition does not get triggered. Not sure why, had to add extra few px to make it work.
on mac computers, the condition below isn't met because of a small offset (~1px) we updated the condition like so (window.innerHeight + window.pageYOffset) >= document.body.offsetHeight - 2
thx @Dekel ! actually, we find out that window.pageYOffset is a float on mac. Our final solution is (window.innerHeight + Math.ceil(window.pageYOffset + 1)) >= document.body.offsetHeight.
Doesn't work for cases where the body has a style that sets the height to 100%
the comment by @Raphaël saved my sleeps! in mac there's 1 px problem and his comment really helped me solve it!! thanks to you man!! God bless you!
L
Lex

The accepted answer did not work for me. This did:

window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >= document.body.scrollHeight) {
      // you're at the bottom of the page
      console.log("Bottom of page");
    }
};

If you're looking to support older browsers (IE9) use the alias window.pageYOffset which has slightly better support.


does not work in IE10/11. Check Dekel's answer (stackoverflow.com/questions/9439725/…) for IE support. Worked for me
The other answers triggered the console.log() every time I scrolled, not just when I was at the bottom of the page. This answer worked for me on Chrome.
If you get rid of window.scrollY, which doesn't work in i.e. or edge, this is a decent answer. Replace with: (window.innerHeight + window.pageYOffset) >= document.body.scrollHeight
This works even when you have the body set to a min-height of 100%.
same, this seems to be the best version - works for mac aswell
p
pasztorpisti

I was searching for an answer but haven't found an exact one. Here is a pure javascript solution that works with latest Firefox, IE and Chrome at the time of this answer:

// document.body.scrollTop alone should do the job but that actually works only in case of Chrome.
// With IE and Firefox it also works sometimes (seemingly with very simple pages where you have
// only a <pre> or something like that) but I don't know when. This hack seems to work always.
var scrollTop = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;

// Grodriguez's fix for scrollHeight:
// accounting for cases where html/body are set to height:100%
var scrollHeight = (document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight;

// >= is needed because if the horizontal scrollbar is visible then window.innerHeight includes
// it and in that case the left side of the equation is somewhat greater.
var scrolledToBottom = (scrollTop + window.innerHeight) >= scrollHeight;

// As a bonus: how to scroll to the bottom programmatically by keeping the horizontal scrollpos:
// Since window.innerHeight includes the height of the horizontal scrollbar when it is visible
// the correct vertical scrollTop would be
// scrollHeight-window.innerHeight+sizeof(horizontal_scrollbar)
// Since we don't know the visibility/size of the horizontal scrollbar
// we scroll to scrollHeight that exceeds the value of the
// desired scrollTop but it seems to scroll to the bottom with all browsers
// without problems even when the horizontal scrollbar is visible.
var scrollLeft = (document.documentElement && document.documentElement.scrollLeft) || document.body.scrollLeft;
window.scrollTo(scrollLeft, scrollHeight);

This almost worked for me, but I had to use ((document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight) instead of just document.body.scrollHeight to account for cases where html/body are set to height:100%
@Grodriguez Thanks for the info! It may come handy for us in the future! :-)
Your first comment saved me from meaningless struggle on the Firefox console with document.body.scrollTop. Thanks.
I
Ifeanyi Amadi

This works

window.onscroll = function() {

    // @var int totalPageHeight
    var totalPageHeight = document.body.scrollHeight; 

    // @var int scrollPoint
    var scrollPoint = window.scrollY + window.innerHeight;

    // check if we hit the bottom of the page
    if(scrollPoint >= totalPageHeight)
    {
        console.log("at the bottom");
    }
}

If you're looking to support older browsers (IE9) replace window.scrollY with window.pageYOffset


this work with react in 2019. work with body 100% height, worth with html 100% height. work with chrome, safari, firefox, edge.
Just a note: naming should be changed - variables should be switched. Because scrollHeight shows the total page height, and totalHeight shows current scroll point, so it's a bit confusing.
J
Jeremy Bernier

If you're setting height: 100% on some container <div id="wrapper">, then the following code works (tested in Chrome):

var wrapper = document.getElementById('wrapper');

wrapper.onscroll = function (evt) {
  if (wrapper.scrollTop + window.innerHeight >= wrapper.scrollHeight) {
    console.log('reached bottom!');
  }
}

i
itay yahalom
window.onscroll = function(ev) {
    if ((window.innerHeight + Math.ceil(window.pageYOffset)) >= document.body.offsetHeight) {
        alert("you're at the bottom of the page");
    }
};

This Answer will fix edge cases, this is because pageYOffset is double while innerHeight and offsetHeight are long, so when the browser gives you the info, you may be a pixel short. For example: on bottom of the page we have

true window.innerHeight = 10.2

true window.pageYOffset = 5.4

true document.body.offsetHeight = 15.6

Our calculation then becomes: 10 + 5.4 >= 16 which is false

To fix this we can do Math.ceil on the pageYOffset value.

Hope that helps.


C
Craig Poole

I've just started looking at this and the answers here helped me, so thanks for that. I've expanded a little so that the code is safe all the way back to IE7:

Hope this proves useful for someone.

Here, have a Fiddle ;)

    <!DOCTYPE html>
<html>
<head>
    <style>
        div {
            height: 100px;
            border-bottom: 1px solid #ddd;
        }

        div:nth-child(even) {
            background: #CCC
        }

        div:nth-child(odd) {
            background: #FFF
        }

    </style>
</head>

<body>
<div></div><div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</body>

<script type="text/javascript">
console.log("Doc Height = " + document.body.offsetHeight);
console.log("win Height = " + document.documentElement.clientHeight);
window.onscroll = function (ev) {
    var docHeight = document.body.offsetHeight;
    docHeight = docHeight == undefined ? window.document.documentElement.scrollHeight : docHeight;

    var winheight = window.innerHeight;
    winheight = winheight == undefined ? document.documentElement.clientHeight : winheight;

    var scrollpoint = window.scrollY;
    scrollpoint = scrollpoint == undefined ? window.document.documentElement.scrollTop : scrollpoint;

    if ((scrollpoint + winheight) >= docHeight) {
        alert("you're at the bottom");
    }
};
</script>
</html>

Sort of works. But it is not very accurate. It considers that it is scrolled to the bottom as long as you are within around 16px of the bottom.
D
Darshna Rekha

Try this method if you've had no luck with the others.

window.onscroll = function() { const difference = document.documentElement.scrollHeight - window.innerHeight; const scrollposition = document.documentElement.scrollTop; if (difference - scrollposition <= 2) { alert("Bottom of Page!"); } }


Z
Zihan Zhang
$(document).ready(function(){
    $('.NameOfYourDiv').on('scroll',chk_scroll);
});

function chk_scroll(e)
{
    var elem = $(e.currentTarget);
    if (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight()) 
    {
        alert("scrolled to the bottom");
    }

}

idk a different perspective. But the accepted answer is better for sure
E
Eka putra

if you love jquery

$(window).scroll(function() {
  if($(window).scrollTop() + $(window).height() >= $(document).height()) {
    // doSomethingHere();
  }
});

And who doesn't love jQuery…
@JoshHabdas browsers
c
cnnr
const handleScroll = () => {
    if (Math.round(window.scrollY + window.innerHeight) >= Math.round(document.body.scrollHeight)) {
        onScroll();
    }
};

This code worked for me in Firefox and IE as well.


C
CheeseFrog

New solution.

One issue stems from a lack of a standard main scrolling element. Recently implemented document.scrollingElement can be used to attempt to overcome this. Below is a cross-browser solution with fallback:

function atEnd() {
    var c = [document.scrollingElement.scrollHeight, document.body.scrollHeight, document.body.offsetHeight].sort(function(a,b){return b-a}) // select longest candidate for scrollable length
    return (window.innerHeight + window.scrollY + 2 >= c[0]) // compare with scroll position + some give
}
function scrolling() {
    if (atEnd()) 
        //do something
}
window.addEventListener('scroll', scrolling, {passive: true});

It works, thank you a lot
C
Coldark

Surprisingly none of the solutions worked for me. I think it's because my css was messed up, and body didn't wrap around all of the content when using height: 100% (don't know why yet). However while looking for a solution I've came up with something well... basically the same, but maybe it's worth to look at - I'm new into programming so sorry if it's doing the same slower, is less supported or something like that...

window.onscroll = function(evt) {
  var check = (Element.getBoundingClientRect().bottom - window.innerHeight <= 0) ? true : false;
  if (check) { console.log("You're at the bottom!"); }
};

v
vhs

Using defaultView and documentElement with functional code snippet embedded:

const { defaultView } = document; const { documentElement } = document; const handler = evt => requestAnimationFrame(() => { const hitBottom = (() => (defaultView.innerHeight + defaultView.pageYOffset) >= documentElement.offsetHeight)(); hitBottom ? console.log('yep') : console.log('nope') }); document.addEventListener('scroll', handler);

scroll down


P
Possible 11

As above mentioned code may not work on all the devices and browsers. Below is the tested working code that will compatible with all the major devices (iPhone, Android, PC) in all the browsers (Chrome, IE, Edge, Firefox, and Safari).

window.onscroll = function(ev) { var pageHeight = Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight ); if ((window.innerHeight + window.scrollY) >= pageHeight) { console.log("You are at the bottom of the page."); } };

Keep scrolling the page till end...


O
Oussama Essamadi

You can check if the combined result of the window's height and scroll top is bigger than that of the body

if (window.innerHeight + window.scrollY >= document.body.scrollHeight) {}


P
PJately

Two solutions I found that worked for me:

  window.addEventListener('scroll', function(e) {
    if (
      window.innerHeight + document.documentElement.scrollTop ===
      document.documentElement.offsetHeight
    ) {
      console.log('You are at the bottom')
    }
  })

And the other:

  window.addEventListener('scroll', function(e) {
    if (
      window.innerHeight + window.pageYOffset ===
      document.documentElement.offsetHeight
    ) {
      console.log('You are at the bottom')
    }
  })

I think you swapped the term top and bottom. Your solution fired up being at top :-)
Hey @m3nda, Which solution are you referring to? Both seem to fire at the bottom for me...
I tried both of them and where fired when in the top of the page (upper content), opposite to bottom (when you scrolled the full page to it's end). I double checked that in both Chrome and Firefox. Btw, solution of @Ifeanyi Amadi worked as expected. Regards.
D
Derek Dawson

The simplest way using vanilla javascript

container.addEventListener('scroll', (e) => {
  var element = e.target;
  if (element.scrollHeight - element.scrollTop - element.clientHeight <= 0) {
    console.log('scrolled to bottom');
  }
});

h
human

I simply place a small image at the bottom of my page with loading="lazy" so the browser is only loading it when the user scrolls down. The image then trigers a php counter script which returns a real image

 <img loading="lazy" src="zaehler_seitenende.php?rand=<?=rand(1,1000);?>">

 <?php
 @header("Location: https://domain.de/4trpx.gif");

h
hfontanez

I had to come up with a way (in Java) to systematically scroll down looking for a component for which I didn't know the correct XPath (long story, so just play along). As I just stated, I needed to scroll down while looking for a component and stop either when the component was found or the bottom of the page was reached.

The following code snippet controls the scrolling down to the bottom of the page:

JavascriptExecutor js = (JavascriptExecutor) driver;
boolean found = false;
long currOffset = 0;
long oldOffset = 0;
do
{
    oldOffset = currOffset;
    // LOOP to seek the component using several xpath regexes removed
    js.executeScript("window.scrollBy(0, 100)");
    currOffset = (Long)js.executeScript("var offset = window.window.pageYOffset; return offset;");
} while (!found && (currOffset != oldOffset));

By the way, the window is maximized before this code snippet is executed.


Java is not JavaScript.
@miken32 If you downvoted this answer because "Java is not Javascript", you didn't look at the code very well. I am invoking Javascript inside a Java application, but the code that does the scrolling IS Javascript.