0

I'm using a "universal" piece of js that should detect if the user has scrolled to the bottom of the document:

 $(window).scroll(function() {
        if ($(window).scrollTop() == $(document).height() - $(window).height()) {
            //ajax code here
        }
    });

As the user scrolls, new content should load via the ajax call.

I would have expected the code to fire when I scroll DOWN, but the condition is actually firing when I scroll back to the TOP of the page, so it's basically doing the opposite of what it's "supposed" to do.

I've seen this solution being used in many examples, such as: https://stackoverflow.com/a/17078097/1623095

My debugging messages:

console.log($(window).scrollTop());
console.log($(document).height());
console.log($(window).height());

These output when scrolling to the top:

0 
1956 
1956 

And bottom:

961 
1956
1956 

The only plugin being loaded in my page is jquery (1.10.0.min), due to the nature of the project, I cannot link to the page.

Thoroughly confused by the dom behavior here.

Community
  • 1
  • 1
Jorg Ancrath
  • 1,387
  • 8
  • 33
  • 59

1 Answers1

1

I solved this some time before for someone else.

Have a look here:

Code

$(window).scroll(function () {
        //- 10 = desired pixel distance from the bottom of the page while scrolling)
        if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
            var box = $("#scrollbox");
            //Just append some content here
            box.html(box.html() + "<br />fa");
        }
});

Fiddle

Just place your ajax code where I extended the content with simple html breaks

Community
  • 1
  • 1
Steini
  • 2,628
  • 13
  • 22
  • Are you boored or something that you keep improving my post? I dont think we need this duplicate answer here – Steini Jul 09 '14 at 09:57
  • The condition is being triggered when I scroll anywhere, not just the bottom of the page, which is not the desirable result at all. – Jorg Ancrath Jul 09 '14 at 09:58
  • No, its firing when you scroll down and was tested. You are doing something wrong. Ofcourse your scrolling element must have atleast as much height as current browser window or it will think it is already at the bottom so you should use min-height for your main content container. – Steini Jul 09 '14 at 10:17