views:

116

answers:

2

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

+1  A: 

$(document).scrollTop() should give you the position of scrollbar. you check that against document height. then fade in or out the div.

Funky Dude
+1  A: 

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"&gt;&lt;/script&gt;
        <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().

BalusC
Thanks but this doesnt work :(
Kenan
Did you check the margins? I updated the answer to include an SSCCE.
BalusC
Yea, margin is 0, I'm using CSS reset. And also Im using jQuery 1.3.2?
Kenan
Hmm, you're right, it didn't work in Firefox (Editplus here has IE7 as builtin browser). The viewport is actually higher in FF. I'll investigate if that's to be expected. Update: funny, `body.onscroll` is not supported in FF.
BalusC
I replaced `body.onscroll` by `window.onscroll` and `==` by `<=`.
BalusC
I found misstake, it should be: $(window).scroll not $('body') Thanks
Kenan
Is there anyway to show content when user reach bottom-200px, for example. So not exactly the bottom, rather than 200px before? Thanks one more time
Kenan
Substract the body height with this value.
BalusC