DotnetDude
DotnetDude

Reputation: 11807

Scrolling in JQuery mobile

I am creating an application using JQuery Mobile which needs to support both iOS and Android. (I am using PhoneGap). Does scrolling on long pages work by default or do I need to set up my divs to support scrolling. How is scrolling on iOS different from an android device?

Also, is there a way to make a ajax call when the user scrolls to the bottom of the page to retrieve more content?

Any help is appreciated.

Upvotes: 0

Views: 7763

Answers (2)

Jasper
Jasper

Reputation: 75993

1) jQuery Mobile 1.1.0 uses the browser's native scrolling so it seems natural on every supported platform.

jQuery Mobiles does however require the following pseudo-page structure:

<div data-role="page">
    <div data-role="header">
        ...
    </div>
    <div data-role="content">
        ...
    </div>
    <div data-role="footer">
        ...
    </div>
</div>

If you follow this structure, the more you add to the data-role="content" section, the longer the page will be.

2) You can set an event handler for the scroll event to detect the user scrolling and see how far down the page the user is:

//you don't want to set a bunch of AJAX requests at once,
//so set a flag so only one will go off at a time
var ajaxOK = true;
$(window).on('scroll', function () {
    var yDistance = $('html, body').scrollTop();

    //here you can check how far down the user is and do your AJAX call
    if ((yDistance + $(window).height()) > ($.mobile.activePage.children('.ui-content').height() - 150)) {
        //the user is within 150px of the bottom of the page
        if (ajaxOK === true) {
            ajaxOK = false;
            $.ajax({ ... });
        }
    }
});

Then in your callback function for the AJAX call you set ajaxOK = true; so that when the user scrolls to the bottom again it will fire.

Here's a quick break-down of the if/then statement in the scroll event handler:

(yDistance + $(window).height()) > ($.mobile.activePage.children('.ui-content').height() - 150)
  1. (yDistance + $(window).height()): the scroll-distance plus the view-port height, to find the bottom of the page's Y coordinate.
  2. ($.mobile.activePage.children('.ui-content').height() - 150): the height of the current page minus a buffer of 150px so the user can get within 150px and the AJAX call will occur

Upvotes: 2

Shawn
Shawn

Reputation: 196

Scrolling should happen automatically if you overflow the browser window. For infinite scrolling you can try http://www.infinite-scroll.com/.

If you are using the listview for jquery mobile you may need to call the refresh event after adding more list view items to the dom to get the filtering behavior and styling to work.

Upvotes: 0

Related Questions