How to detect if browser window is scrolled to bottom?
Asked Answered
T

24

270

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?

Tripetalous answered 24/2, 2012 at 23:53 Comment(3)
This one is worked in Angular 6 --> https://mcmap.net/q/56333/-how-to-detect-scroll-to-bottom-of-html-elementGliwice
Duplicate of stackoverflow.com/questions/3898130 after allByran
Does this answer your question? Check if a user has scrolled to the bottom (not just the window, but any element)Berty
S
372
window.onscroll = function(ev) {
    if ((window.innerHeight + Math.round(window.scrollY)) >= document.body.offsetHeight) {
        // you're at the bottom of the page
    }
};

See demo

Shwalb answered 25/2, 2012 at 0:3 Comment(13)
Works in all major browsers except IE (my IE version is 11)Adaptive
Does not work when html/body elements are set to 100% (so that the body fills the entire viewport height)Flageolet
Use document.documentElement.scrollTop instead of window.scrollY for IE. Not sure which, if any, versions of IE support window.scrollY.Avalanche
Does not work in Chromium Version 47.0.2526.73 Built on Ubuntu 14.04, running on elementary OS 0.3.2 (64-bit)Equalize
I used document.body.scrollHeight instead of offsetHeight (in my case, offsetHeight was always smaller that the window.innerHeight)Cervin
@KarlMorrison can you try the bounty-awarded answer (by @Dekel) with your browser?Sepulchre
@Batandwa, document.documentElement.scrollTop doesn't work with Safari, but window.scrollY does.Lafave
This appears to be outdated.Cassy
Awesome.. It's works too in react-native webview github.com/react-native-community/react-native-webview/blob/…Mayolamayon
Should be : if(Math.ceil(window.innerHeight + window.scrollY) >= document.body.scrollHeight)Kura
Incorrect nowadays, see stackoverflow.com/questions/55419779Lassitude
In the case, html/body is set to 100% like @Flageolet mentioned, you can try to check if the <Footer> element is in the viewport. See how I fixed this at: deniapps.com/blog/hide-anchor-ads-when-scrolling-to-the-bottom.Mola
For modern browsers, use documentElement's scroll height, which would be root html tag, instead of body's offset height or scroll height. (window.innerHeight + window.scrollY) >= document.documentElement.scrollHeightDyne
N
164

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.

Natural answered 2/11, 2016 at 0:55 Comment(11)
Confirmed working on FF, Chrome, IE10, Chrome for Android. Thank you @Dekel!Sepulchre
+1 Well done. I have tested this in a broad set of current browsers and have confirmed that it works. The other options do not cover all the browsers. +1 for awarding a bounty to this answer as it emphasizes it as the correct answer.Incorporate
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.Talented
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 - 2Overweigh
@Raphaël thanks for the comment, I updated the answer accordingly.Natural
thx @Natural ! 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.Overweigh
Can run into trouble when users change the zoom level in their browser. Can resolve with the following: Math.ceil(window.innerHeight + window.pageYOffset) >= document.body.offsetHeightTeal
Doesn't work for cases where the body has a style that sets the height to 100%Creuse
Sorry I should have been more specific, the html also needs to have 100% height. Working example: jsfiddle.net/jontrausti/qd95vcf3Creuse
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!Interpleader
I'm quoting MDN: The pageYOffset property is an alias for the scrollY property: window.pageYOffset === window.scrollY; // always trueOrtego
G
92

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.

Gaytan answered 7/7, 2015 at 9:1 Comment(4)
does not work in IE10/11. Check Dekel's answer (#9440225) for IE support. Worked for meSomnambulate
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.Slowwitted
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.scrollHeightLandsman
This works even when you have the body set to a min-height of 100%.Phlebotomy
D
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);
Digestion answered 14/3, 2014 at 1:38 Comment(3)
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%Flageolet
Your first comment saved me from meaningless struggle on the Firefox console with document.body.scrollTop. Thanks.Kronstadt
Excellent answer, this snippet here is just for modern browsers, won't work for IE 11, const scrolledToBottom = (window.innerHeight + window.scrollY) >= document.documentElement.scrollHeightDyne
O
32

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

Outhaul answered 12/10, 2017 at 20:36 Comment(2)
this work with react in 2019. work with body 100% height, worth with html 100% height. work with chrome, safari, firefox, edge.Frightfully
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.Magnification
B
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!');
  }
}
Brochu answered 29/3, 2015 at 20:0 Comment(0)
C
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.

Centrifugal answered 7/6, 2017 at 20:46 Comment(0)
S
6

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!"); 
    }   
}
Seurat answered 20/11, 2020 at 1:43 Comment(0)
H
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>
Halleyhalli answered 7/11, 2014 at 16:51 Comment(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.Fraudulent
T
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});
Trimeter answered 18/5, 2021 at 8:35 Comment(0)
D
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>
Distinctly answered 26/1, 2022 at 7:56 Comment(1)
window.innerHeight + window.scrollY might give a result with decimal place, I wrapped it with Math.ceil(window.innerHeight + window.scrollY)Corundum
B
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');
  }
});
Bothersome answered 13/4, 2022 at 20:52 Comment(0)
O
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");
    }

}
Orchestral answered 14/9, 2016 at 16:41 Comment(0)
A
3

if you love jquery

$(window).scroll(function() {
  if($(window).scrollTop() + $(window).height() >= $(document).height()) {
    // doSomethingHere();
  }
});
Apterous answered 19/10, 2018 at 17:15 Comment(2)
And who doesn't love jQuery…Civilly
@JoshHabdas browsersCharbonneau
C
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>
Civilly answered 1/2, 2019 at 11:12 Comment(0)
D
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.

Douty answered 13/8, 2019 at 7:37 Comment(0)
H
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");
    }
  })
Heptameter answered 4/8, 2022 at 14:53 Comment(0)
A
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!"); }
};
Amitosis answered 24/12, 2015 at 1:18 Comment(0)
M
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) {}

Molnar answered 27/2, 2020 at 16:32 Comment(0)
U
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')
    }
  })
Unbowed answered 8/7, 2020 at 23:40 Comment(3)
I think you swapped the term top and bottom. Your solution fired up being at top :-)Rosecan
Hey @m3nda, Which solution are you referring to? Both seem to fire at the bottom for me...Unbowed
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.Rosecan
Y
0

This check works ok for me with lazy loading

window.onscroll = () => {
    if (Math.ceil(window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
        alert('Bottom!');
    }
};
Yingling answered 27/4, 2023 at 15:19 Comment(0)
H
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');

    }
});
Hypochromia answered 22/8, 2023 at 14:15 Comment(0)
T
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));
Tokyo answered 14/12, 2023 at 21:19 Comment(0)
Y
-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");
Yeargain answered 19/1, 2022 at 20:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.