jQuery Mobile & iScroll: Image Scaling and Panning
Just like the regular web, mobile web apps need to work with images. Common wisdom says that you should optimize images for mobile web apps, but what does that mean? What looks good on my Nexus One isn't going to look to hot on my iPad. The reality is that you are going to have to scale images for the user's device. But what if the user wants to see the image in all of its high resolution glory? This where panning comes in. The question is, "How do you pan an image on a mobile device?
One solution is to use iScroll 4. Written by Matteo Spinelli, iScroll 4 is a JavaScript plugin which uses CSS3 transformations to smoothly move DOM elements. For more information about how iScroll 4 works please visit Matteo's site.
The demo app consist of two pages. The first page shows the image scaled to fit the display. During its pageshow event handler it dynamically sizes jQuery Mobile's content area. It then uses these dimensions and HTML to scale the image. If you only supply one dimension of an <img> tag, HTML supplies the other and maintains the image's aspect ratio.
The second page instantiates an iScroll object during the pageshow event handler and destroys it in the pagehide event handler. The magic of the iScroll is in the CSS, basically there is a viewport called 'wrapper', which is sized to the content area of the jQuery Mobile page. Nested in the viewport is the total viewable image, which is named 'scroller'. The size of the scroller is determined dynamically using jQuery’s dimension methods to measure an unscaled and hidden version of the image named 'hiddenPic'. Please note how the hiddenPic is not on any jQuery Mobile page and is taken out of the HTML flow.
Unfortunately for all of the Windows Phone 7 fans, iScroll 4 is not compatible with it. I don't if this will change in the future, but for now this code is not a solution for WP7.
iScroll 4 combined with jQuery Mobile gives mobile web apps the look and feel expected only of device apps. In a future tutorial I will throw PhoneGap into the mixed. The code for this tutorial is on GitHub.