How to show div when user reach bottom of the page?

Kenan picture Kenan · May 4, 2010 · Viewed 27.3k times · Source

When user scrolls to the bottom of the page I want to show some div, with jQuery of course. And if user scrolls back to he top, div fade out. So how to calculate viewport (or whatever is the right name) :)

Thanks

Answer

BalusC picture BalusC · May 4, 2010

This must get you started:

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2768264</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(document).ready(function() {
                $(window).scroll(function() {
                    if ($('body').height() <= ($(window).height() + $(window).scrollTop())) {
                        alert('Bottom reached!');
                    }
                });
            });    
        </script>
        <style>
            body { margin: 0; }
        </style>
    </head>
    <body>
        <p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p
        <p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p
        <p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p
        <p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p
    </body>
</html>

This assumes that body has a margin of 0. Else you'll need to add the top and bottom margin to the $('body').height().