Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Mobile User scroll to bottom

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

like image 726
Rory Standley Avatar asked Feb 15 '12 16:02

Rory Standley


2 Answers

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");
        }
    }
});
like image 157
davehale23 Avatar answered Oct 13 '22 21:10

davehale23


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!");
    }
});
like image 32
Mark Boulder Avatar answered Oct 13 '22 20:10

Mark Boulder