|

jQuery Mobile Scrolling

jQuery Mobile, JQM, is a great cross-platform web development framework, but it isn’t perfect. Its need to be cross-platform limits its ability to do a few things, such as interior scrolling. Native applications can easily do interior scrolling. Android and iPhone applications can easily leave the header and footer in place so users can scroll the interior vertically or horizontally. Luckily there is a way to add app-like interior scrolling to jQuery Mobile — a JavaScript plug-in named iScroll4.

Introducing iScroll 4

iScroll4 was created by developer Matteo Spinelli and is available for download on his web site at, http://cubiq.org/iscroll-4. The current version is 4.1.7, and it was released on July 3, 2011. iScroll depends upon CSS transforms, which Internet Explorer doesn’t support so, sorry Windows Phone 7. iScroll has a lot of features besides scrolling, but we will save those features for another day and just concentrate on scrolling in this article. There are two versions of the iScroll plug-in: regular and lite. The lite version is less than half of the size of the regular version, and doesn’t support any extra goodies or the desktop. We will use the lite version in the demo program but if you want to use some of the extra goodies feel free to use the full version instead.

Before we get started on iScroll, I am sure you are asking why it is necessary since jQuery Mobile version 1.1.0 has added a much improved ability to fix the position of the header and footer using CSS position:fixed. In general this is an acceptable solution for vertical scrolling of the content area, but it is not a true interior scroll. What is actually happening is the content area extends from the top to the bottom of the viewport and the header and footer are position on top of it. I know you may be thinking that it is the same difference, but what happens if instead of wanting to vertically scroll the entire content area, you only wanted to scroll a subset, such as a <div> region or you want to scroll horizontally? In this case, using position:fixed on the header and footer won’t help you. You still need iScroll.

How it works

iScroll works by nesting a bigger region inside of a smaller one. The smaller region serves as a viewport into the bigger region. In theory iScroll can scroll horizontally and vertically at the same time. In practice, users would not expect to be able to scroll diagonally, so we limit our scrolling to one direction at a time. The location of the viewport is changed by iScroll using CSS3 transformations. iScroll also takes care of all of the users interaction with it. Once you set it up, iScroll does all of the grunt work. The trick is setting it up. Only one line of JavaScript is need to invoke iScroll, since the majority of the set up is the CSS style sheet.

An easy way to imagine iScroll is to think of the big scrolling region as the scroller and the smaller viewport region as the wrapper. Inside of the scroller are tiles. A <ul> element is used as a container for all of the tiles and each <li> element represents an individual tile. CSS is used to set each <li> to display:block and float:left. This causes them to naturally stack either vertically or horizontally depending on their container.

Vertical scrolling

To scroll vertically we make the scroller’s height greater than its width. To determine the scroller’s height we use the following formula:

scroller height = (number of tiles + 1) * tile height

We set the widths of the scroller and tiles to be equal, by setting them to 100%. This means that only one tile can be on any row, so the tiles stack vertically.

Horizontal scrolling

Because we set each <li> to float:left, the tiles will naturally stack side by side when given enough width to do so. Like the height above, the formula for the width is simple:

scroller width = (number of tiles + 1) * tile width
/* only for vertical scrolling */
#verticalWrapper {
    width: 100%;     /* will be the same as the width of the content area */
    height: 240px;   /* will be changed to the height of the content area */
    overflow: auto;
}

#verticalScroller {
    width: 100%;
    height: 3240px;  /* max number scroll elements + 1 times their height */
    background-color: #f00;
}

#verticalScroller li {
    width: 100%;
    height: 120px;  /* this is the height of an individual element */
    border-top: 1px solid #ccc;
    border-bottom: 1px solid #fff;
}

Wrapping things

In the demo we are making the content window is our wrapper. How do we determine its dimensions? The width is easy: simply set it to 100% and it will fill its container. Height is not so easy. While you could set the height to 100%, it won’t work since its parent doesn’t have a height set either. We could simply pick a number and set height to it, but every mobile web developer should cringe at that suggestion. There are simply too many devices for a hardcoded value to look good universally. Instead we use jQuery’s dimension methods to help us determine the size of the content area.

What we do is to determine the height of the window then subtract the heights of the header and footer from it. We then use JavaScript via jQuery’s CSS methods to update the wrapper’s height. Before we can get any valid dimensions we need to wait until jQuery Mobile triggers a pageshow event. Once it occurs it means JQM has initialized, is ready to render the page, and the dimension values are valid.

init = function () {
    width = $(window).width();
    height = $(window).height();
    headerHeight = $("header", $.mobile.activePage).height();
    footerHeight = $("footer", $.mobile.activePage).height();
    contentHeight = height - headerHeight - footerHeight;
};

var pageshow = function () {
        RocknCoder.Dimensions.init();
        // determine the height dynamically
        var dim = RocknCoder.Dimensions.getContent();
        $("#horizontalWrapper").css('height', dim.height);
        $("#verticalWrapper").css('height', dim.height);
    };

Smooth scrolling

With the proper CSS and HTML in place we activate iScroll by instantiating it with the new instruction in our pageshow event handler. Being good coders we also destroy our scroll in the pagehide event handler. This will free the resources iScroll is using and keep us from leaking memory. One other thing we should do is keep the content of the scroll region as small as possible. The more things we put in it, the slower our scroll will be.

RocknCoder.Pages.verticalPage = (function () {
    var myScroll,
        pageshow = function () {
            myScroll = new iScroll('verticalWrapper');

        },
        pagehide = function () {
            myScroll.destroy();
            myScroll = null;
        };
    return {
        pageshow: pageshow,
        pagehide: pagehide
    };
}());

Summary

iScroll 4 is a free JavaScript plug-in, while not specifically designed for use with jQuery Mobile, it is compatible with it. Add it to your own mobile web site to enhance your UI.

To access the source code directly, you can go here: JQMScrolling on GitHub.

Safari Books Online has the content you need

Take advantage of these jQuery mobile resources in Safari Books Online:

Pro jQuery Mobile will teach you how to create themable, responsive, native-looking applications for iOS, Android, Windows Phone, Blackberry, and more.
jQuery Mobile provides a practical approach to using jQuery Mobile to quickly develop web-based applications for mobile devices.
jQuery Mobile First Look will show you the features of the jQuery Mobile framework, what they do, and how they can be used.
jQuery, jQuery UI, and jQuery Mobile: Recipes and Examples is a practical “cookbook” packed with realistic, easy-to-use solutions for making the most of jQuery Core, jQuery UI, and jQuery Mobile.

About this author

A designer and developer of software since 1979, Troy began his career writing games in assembly and C. Since then he has written code in C++, C#, Objective-C, Java, JavaScript and even a smidgen of Python. Along the way, some of his titles have won awards, he became a Microsoft Certified Solution Developer, and in 2012, he won a developer challenge at a local Microsoft Windows Phone Unleashed event. His passion since 2007 has been mobile and mobile web development. In 2011, he joined the mobile development team at Kelley Blue Book. His small team is responsible for the KBB.com application for iPhone, Android, and Windows Phone 7 and the mobile versions of KBB.com. Troy also spends time talking to developer groups and maintaining his blog, The Rock n Coder.

About Safari Books Online

Safari Books Online is an online learning library that provides access to thousands of technical, engineering, business, and digital media books and training videos. Get the latest information on topics like Windows 8, Android Development, iOS Development, Cloud Computing, HTML5, and so much more – sometimes even before the book is published or on bookshelves. Learn something new today with a free subscription to Safari Books Online.
|

Comments are closed.