278

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?

3

24 Answers 24

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

See demo

13
  • 57
    Does not work when html/body elements are set to 100% (so that the body fills the entire viewport height)
    – Grodriguez
    Commented Oct 23, 2014 at 9:47
  • 8
    Use document.documentElement.scrollTop instead of window.scrollY for IE. Not sure which, if any, versions of IE support window.scrollY.
    – Batandwa
    Commented Oct 27, 2014 at 11:33
  • 3
    Does not work in Chromium Version 47.0.2526.73 Built on Ubuntu 14.04, running on elementary OS 0.3.2 (64-bit)
    – basickarl
    Commented Jan 5, 2016 at 23:48
  • 16
    I used document.body.scrollHeight instead of offsetHeight (in my case, offsetHeight was always smaller that the window.innerHeight)
    – Oliver
    Commented Apr 25, 2016 at 11:16
  • 1
    @KarlMorrison can you try the bounty-awarded answer (by @Dekel) with your browser?
    – Basj
    Commented Nov 2, 2016 at 21:48
168
+100

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");
    }
};
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>

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.

11
  • 3
    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. Commented Apr 27, 2017 at 11:34
  • 7
    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
    – Raphaël
    Commented Jun 20, 2017 at 16:55
  • 4
    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.
    – Raphaël
    Commented Jun 21, 2017 at 13:46
  • 2
    Doesn't work for cases where the body has a style that sets the height to 100% Commented Sep 25, 2018 at 17:36
  • 1
    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!
    – Sjd
    Commented Nov 18, 2021 at 19:22
93

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.

4
  • 1
    does not work in IE10/11. Check Dekel's answer (stackoverflow.com/questions/9439725/…) for IE support. Worked for me Commented Dec 14, 2016 at 8:41
  • 1
    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.
    – Defcronyke
    Commented Sep 24, 2017 at 21:00
  • 1
    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 Commented Jan 9, 2018 at 9:29
  • This works even when you have the body set to a min-height of 100%. Commented Feb 3, 2021 at 9:59
36

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);
3
  • 4
    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
    Commented Oct 23, 2014 at 9:46
  • Your first comment saved me from meaningless struggle on the Firefox console with document.body.scrollTop. Thanks.
    – thiras
    Commented Feb 11, 2021 at 19:46
  • Excellent answer, this snippet here is just for modern browsers, won't work for IE 11, const scrolledToBottom = (window.innerHeight + window.scrollY) >= document.documentElement.scrollHeight Commented Jan 26, 2023 at 2:45
33

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

2
  • 1
    this work with react in 2019. work with body 100% height, worth with html 100% height. work with chrome, safari, firefox, edge.
    – angry kiwi
    Commented Sep 7, 2019 at 13:07
  • 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. Commented May 9, 2020 at 7:37
8

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!');
  }
}
7

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!"); 
    }   
}

6
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.

5

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>
1
  • 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.
    – Peter Hall
    Commented Jan 5, 2016 at 1:20
4

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});
0
4

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.");
    }
};
<html>
<body>
  <div style="width:100%; height:1500px">
    <p>Keep scrolling the page till end...</p>
  </div>
</body>
</html>

1
  • window.innerHeight + window.scrollY might give a result with decimal place, I wrapped it with Math.ceil(window.innerHeight + window.scrollY) Commented Sep 7, 2022 at 3:45
4

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');
  }
});
3
$(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");
    }

}
0
3

if you love jquery

$(window).scroll(function() {
  if($(window).scrollTop() + $(window).height() >= $(document).height()) {
    // doSomethingHere();
  }
});
2
  • And who doesn't love jQuery…
    – vhs
    Commented Feb 1, 2019 at 11:14
  • 6
    @JoshHabdas browsers Commented Dec 4, 2019 at 14:08
3

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);
<pre style="height:110vh;background-color:fuchsia">scroll down</pre>

3
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.

0
2

I made this function for Mobile Devices and Desktop try it, It's work for me some of comment here is not working on Mobile/Android devices, BTW Thank You for this question. Keep it Up coders!

    window.addEventListener("scroll", function(el) {
    const scrollY = window.scrollY + window.innerHeight + 2;
    const bodyScroll = document.body.offsetHeight;

    console.log("Scroll Y : " + scrollY);
    console.log("Body : " + bodyScroll);

    if(scrollY >= bodyScroll){
      alert("Bottom Page");
    }
  })
1

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) {}

1

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')
    }
  })
3
  • I think you swapped the term top and bottom. Your solution fired up being at top :-)
    – m3nda
    Commented Oct 12, 2020 at 14:45
  • Hey @m3nda, Which solution are you referring to? Both seem to fire at the bottom for me...
    – PJately
    Commented Oct 13, 2020 at 9:20
  • 1
    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.
    – m3nda
    Commented Oct 13, 2020 at 17:01
1

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;
  
  if (check) { console.log("You're at the bottom!"); }
};
0

This check works ok for me with lazy loading

window.onscroll = () => {
    if (Math.ceil(window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
        alert('Bottom!');
    }
};
0

This worked for me note to include the Math.round() function to round off the height to the nearest integer.

window.addEventListener('scroll', function(e) {

    if (Math.round(window.innerHeight + window.scrollY) >= document.body.scrollHeight) {
        alert('bottom');

    }
});
0

I saw the accepted answer didn't take into account margins at the bottom and/or top of the page, so here's my answer:

const body = document.body;
const paddingHeight = body.scrollHeight;
const computedStyle = getComputedStyle(body);
        
const marginTop = parseInt(computedStyle.getPropertyValue("margin-top").match(/[0-9]+/)[0]);
const marginBottom = parseInt(computedStyle.getPropertyValue("margin-bottom").match(/[0-9]+/)[0]);

const borderTop = parseInt(computedStyle.getPropertyValue("border-top").match(/[0-9]+/)[0]);
const borderBottom = parseInt(computedStyle.getPropertyValue("border-bottom").match(/[0-9]+/)[0]);

const bodyHeight = marginTop + borderTop + paddingHeight + borderBottom + marginBottom;

window.onscroll = () => {
    if ((window.innerHeight + window.scrollY) >= bodyHeight) {
       console.log("YAY! :)");
    }
};

If the website uses infinite scrolling you probably also want to wait for the height to update before checking, with something like this:

await new Promise(resolve => setTimeout(resolve, 3000));
-1

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");
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.