7

With the following code, I am trying to find when the user scrolls to the bottom of the page. In JQuery mobile.

$(window).scroll(function(){
     if($(window).scrollTop() == $(document).height() - $(window).height()){
          alert("The Bottom");
     }
});

For now I am just wanting it to output that they have reached the bottom.

My problem is, when the site loads, it will output this message. When I scroll to the bottom it will then output the alert.

Is there a way to stop it doing it for when the page has loaded and only do it when the user has physically scrolled the page?

Thanks

2 Answers2

6

Is it because your content is shorter than your page? Meaning that when it loads, you are already at the bottom. I have tried to replicate your problem here http://jsfiddle.net/qESXR/2/ and it behaves like you want. However if I shorten the content and run it locally on my machine I get the same result you have.
If so, you might check for the height of the page vs height of your html using these

$(window).height();   // returns height of browser viewport

$(document).height(); // returns height of HTML document

like this:

$(window).scroll(function(){
    if($(document).height() > $(window).height())
    {
        if($(window).scrollTop() == $(document).height() - $(window).height()){
          alert("The Bottom");
        }
    }
});
davehale23
  • 4,374
  • 2
  • 27
  • 40
  • Yeah, the data is loaded in dynamically. so the initial load it is empty, but once the data is inserted into the DOM it obviously expands. –  Feb 15 '12 at 16:33
  • Sounds like you need to add the scroll dynamically after you load the content. If so here is a good resource http://stackoverflow.com/questions/4306387/jquery-add-and-remove-window-scrollfunction – davehale23 Feb 15 '12 at 16:39
  • Thank you so much! this has been driving me insane!! –  Feb 15 '12 at 16:39
  • 2
    @Rory: could you perhaps post the solution you ended up with? Thanks! – Adam Jul 17 '12 at 21:54
1

The problem is that jQuery Mobile's page widget treats each "page" as the window as far as scrolling goes. To detect when the user has scrolled to the end, bind the scroll function to $(document) instead:

http://jsfiddle.net/5x6T2/

$(document).scroll(function () {
    if ($(window).scrollTop() + $(window).height() == $(document).height()) {
        alert("Bottom reached!");
    }
});
Mark Boulder
  • 13,577
  • 12
  • 48
  • 78