Jorg Ancrath
Jorg Ancrath

Reputation: 1447

"infinite scroll" code working only for top scrolling

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.

Upvotes: 0

Views: 1440

Answers (1)

Steini
Steini

Reputation: 2783

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

Upvotes: 1

Related Questions